XSS Basics: Cross-Site Scripting
Imagine a guestbook page. A visitor types a message, and your page shows it to everyone. Now imagine the "message" is not words but a piece of code, and your page treats it as part of its own HTML. Every visitor who opens the guestbook now runs that code, with all the power of your site. That is cross-site scripting, or XSS, and it is one of the most common and most damaging web page problems.
The good news is that the cause is simple and the cure is well understood: keep data and code apart. This lesson shows you how.
What You Will Learnβ
- What XSS is, and what an attacker can do with it
- The three types: stored, reflected, and DOM-based
- Why it happens, in one sentence
- How to escape output correctly for each context
- Which DOM methods are safe, and which are not
- How to handle links and addresses supplied by visitors
- What to do when you must allow some HTML
- Which extra layers reduce the damage if something slips through
The Big Ideaβ
XSS happens when untrusted text is turned into markup or code. The fix is to make sure untrusted text always stays text.
- Unsafe and Safe Code
- Context Lab
- Safe or Unsafe?
// UNSAFE: the comment is parsed as HTML
const out = document.querySelector("#comment");
out.innerHTML = comment;
// SAFE: the comment is only ever text
const out = document.querySelector("#comment");
out.textContent = comment;
// SAFE: build elements with code, and set text on them
const li = document.createElement("li");
li.textContent = name;
list.append(li);
Loading the lab...
Answered 0 of 9. Correct: 0.
Each line handles text that a visitor wrote. Is it safe?
In the Context Lab, press the "Attribute breakout" and "Tag injection" presets. Look at how the same text is risky in one context and harmless once encoded, and how each context needs its own kind of encoding.
What an Attacker Can Doβ
Injected code runs as your page, with your origin's full power (HTML Security Basics explains why). Depending on the site, that can mean:
- Reading anything the page can read, including personal information on screen
- Acting as the visitor, for example sending requests, changing settings, or posting messages
- Changing what the page shows, for example adding a fake login form
- Capturing what the visitor types
- Reading cookies and storage that script can access, which is why sensitive cookies should be marked
HttpOnly - Redirecting the visitor to another site
You do not need to know how attacks are written to defend against them. You need to know that any path that lets untrusted text become code is a vulnerability, and to close those paths.
The Three Typesβ
| Type | How the text gets in | Where it is injected | Example |
|---|---|---|---|
| Stored | A visitor saves it (a comment, a profile) | Your server later sends it to other visitors | A malicious comment shown to everyone |
| Reflected | It is in a link or request, such as a search term in the address | Your server echoes it straight back in the response | A crafted link that shows an unescaped search term |
| DOM-based | It is in the address, or another browser-side source | Your own script inserts it into the page, with no server involved | A script that reads the address fragment and writes it with innerHTML |
The cure is the same for all three: escape on output, and use safe methods. What changes is where you apply it: in the server's templates, or in your browser-side code.
Why It Happensβ
Browsers cannot tell the difference between markup you wrote and markup that a visitor wrote, once they are mixed into the same string. If you build HTML by joining strings, the browser parses the result as one document, and everything in it is trusted.
const html = "<p>Hello, " + name + "</p>"; // name is now part of the markup
If name contains something that looks like a tag, the parser creates a tag. The rule that prevents this is simple: never build markup out of untrusted strings. Build it with safe APIs, or escape the strings first.
Escape for the Contextβ
Escaping means replacing characters that have a special meaning with harmless ones. The right replacement depends on where the text is going, because each place has its own special characters:
| Context | Example | What to do |
|---|---|---|
| HTML text | <p>HERE</p> | HTML-escape &, <, >, and quotes |
| Quoted attribute | <input value="HERE"> | HTML-escape, and always quote attributes |
| URL parameter | <a href="/search?q=HERE"> | URL-encode with encodeURIComponent |
| URL as a whole | <a href="HERE"> | Check the scheme against an allow-list |
| JavaScript data | <script>var x = HERE;</script> | Avoid if possible. Otherwise write JSON and escape <, >, & |
| CSS | style="color: HERE" | Avoid. Use a fixed list of allowed values |
The Context Lab above shows the first four. Notice that there is no single "escape everything" function that works everywhere. HTML escaping does not protect a text placed inside a URL, and URL encoding does not protect text placed inside HTML.
You rarely write escaping by hand. Modern template systems and front-end frameworks escape output by default. The danger is in the escape hatches: features with names like "raw", "safe", dangerouslySetInnerHTML, or v-html. Treat each use of one as a security review item.
Use Safe DOM Methodsβ
When you write browser-side code, prefer methods that treat values as text:
| Safe (value stays text) | Unsafe (value is parsed as markup) |
|---|---|
textContent | innerHTML |
createElement and append | insertAdjacentHTML |
setAttribute("title", value) with a fixed attribute name | outerHTML |
element.alt, element.value | document.write |
new Option(text, value) | eval, new Function, string timers |
A habit to build: if you ever write innerHTML =, stop and ask where the string came from. If any part of it can be influenced by a visitor, use textContent or create elements instead. Try the quiz tab above to practise spotting each one.
Do not let visitor text choose an attribute name either. el.setAttribute(name, value) with an attacker-controlled name could set an event handler.
Links and Addresses From Visitorsβ
Any address a visitor can supply, such as a "my website" field on a profile, must be checked before it goes into an href or src. A javascript: address runs code when the link is clicked. Allow only the schemes you expect:
function safeHref(value) {
try {
const url = new URL(value, location.origin);
if (["http:", "https:", "mailto:"].indexOf(url.protocol) !== -1) return url.href;
} catch (e) {}
return "#";
}
link.href = safeHref(userUrl);
This is an allow-list: it names what is permitted and rejects everything else. That is much stronger than a block-list that tries to name every dangerous scheme. Try different addresses in the last section of the Context Lab. For links that open in a new tab, also see noopener.
When You Must Allow Some HTMLβ
Sometimes you do want visitors to use a little formatting, such as bold text in a comment or a rich-text editor. Then escaping everything is too strong, and you need sanitising: removing everything that is not on a list of allowed tags and attributes.
- Use a well-maintained sanitising library, such as DOMPurify, rather than writing your own. Writing a safe HTML sanitiser is surprisingly hard, and home-made regular expressions fail.
- Keep it updated, and configure an allow-list of tags and attributes as small as you can.
- Sanitise at the right time, ideally when the content is shown (or on the server before it is stored and shown), and again if the content moves between systems.
- A simpler option is a safe markup format, such as Markdown, converted by a trusted library that escapes raw HTML.
- Browsers are also adding built-in sanitising features. Support varies, so check current documentation before relying on them.
More Layersβ
No single defence is perfect, so add layers that limit the damage if a mistake slips through:
- Content Security Policy (CSP). Tells the browser which sources of script are allowed, and can block inline scripts and handlers. Even if text gets injected, the browser may refuse to run it. See Content Security Policy.
HttpOnlycookies. A cookie markedHttpOnlycannot be read by script, so injected code cannot steal it. This is set by the server.- Trusted Types. A newer browser feature, available in some browsers, that makes dangerous sinks such as
innerHTMLaccept only values that have passed through code you approved. Support is not universal, so check before you rely on it. - Short sessions and re-checks for sensitive actions. If an attacker does run code, they should not be able to do everything.
- Server-side validation. Reject input that is not shaped as you expect, but never rely on this alone. Validation reduces risk, and escaping prevents it.
Test Your Own Site Safelyβ
You can check whether your own pages escape output without using anything harmful.
- In a text field on your own site, enter a harmless marker such as
<b>test</b>and submit. - Look at where it is shown. If you see the literal characters
<b>test</b>, the output is escaped. If you see test in bold, the text was treated as markup, and you have a gap to fix. - Repeat in every place that shows visitor input: comments, names, search results, error messages, and URL parameters.
- Check the page source (not the DevTools element view) to see exactly what the server sent.
- Add a CSP in report-only mode first, to see what it would block (see the CSP lesson).
- Use an automated scanner on your own site if you have one, and treat it as a helper rather than proof.
Only test sites you own or have written permission to test. Do not try injection strings on other people's sites.
Best Practicesβ
- Escape output by default, using your template system or framework.
- Never build HTML from strings that include untrusted text.
- Prefer
textContentandcreateElementoverinnerHTML. - Escape for the context: HTML, attribute, URL, or script data.
- Use an allow-list for URL schemes and for any HTML you permit.
- Sanitise with a maintained library when you must allow markup.
- Mark sensitive cookies
HttpOnly, and add a Content Security Policy. - Treat escape hatches such as
v-htmlanddangerouslySetInnerHTMLas review items. - Remember data from your own database may have started as visitor input.
- Test your own pages with harmless markers.
Quick Checklistβ
- All visitor text is escaped where it is shown
- No
innerHTML,insertAdjacentHTML, ordocument.writewith untrusted text - Attributes are always quoted
- Visitor-supplied links are checked against a scheme allow-list
- Any allowed HTML goes through a maintained sanitiser
- No use of
evalornew Functionon visitor input - Sensitive cookies are
HttpOnly - A Content Security Policy is in place, or planned
- Every "raw" or "safe" escape hatch has been reviewed
Security and Privacy Notesβ
- Examples on this page are for defence. Use the patterns to protect your own sites, and test only what you own or have permission to test.
- XSS exposes visitors' private information. A single hole can leak personal data. Treat a fix as protecting people, not only the site.
- Do not log or store raw hostile input where it might be shown later without escaping, such as in an admin dashboard. Internal tools are targets too.
- Report problems responsibly. If you find an XSS hole on someone else's site, tell the owner privately, and do not exploit it. Many sites publish a contact at
/.well-known/security.txt. - Never paste real secrets or private data into online tools while testing.
Global Audience Notesβ
- Text comes in every script and direction. Names, searches, and comments can include accents, right-to-left text, and symbols. Escape on the characters that matter to HTML and let the rest through, and test with real multilingual input.
- Set the character encoding to UTF-8 with
<meta charset="utf-8">as early as possible in the head, and send the matching header. A page and server that disagree about the encoding have historically caused escaping problems. See the charset lesson. - Do not strip characters from names to be "safe". Many real names contain apostrophes, hyphens, and non-Latin letters. Escape on output instead.
- Show error messages in the visitor's language, and never echo raw input inside them without escaping.
- Look-alike characters from different alphabets can make addresses and names misleading. Show the real destination of links where it matters.
Common Mistakes to Avoidβ
- Using
innerHTMLfor text that includes visitor input. - Escaping for the wrong context, such as HTML-escaping a value that is placed in a URL.
- Leaving attributes unquoted.
- Trusting data from your own database because "it came from us".
- Stripping or blocking "bad" words instead of escaping on output.
- Writing your own sanitiser with regular expressions.
- Blocking
javascript:only, instead of allowing only known-good schemes. - Escaping only on input, so the text is wrong for other contexts later. Escape on output.
- Using framework escape hatches without review.
- Assuming a CSP means escaping is optional. It is a second layer, not a replacement.
Practice Timeβ
- In the Context Lab, press "Tag injection". Which contexts become risky without encoding?
- Press "Attribute breakout". Which context does it affect, and why?
- Check that the right encoding makes the risk disappear in each one.
- Try three different link addresses in the last section. Which are allowed?
- Take the safe-or-unsafe quiz. Which line surprised you?
- Search your own code for
innerHTML. For each result, where does the string come from? - Replace one with
textContentorcreateElement. - Bonus: add a comment with
<b>test</b>to your own site. Does it show as literal text or as bold?
Quick Recapβ
Click a question to check your answer.
1. What is XSS?
A vulnerability where untrusted text is treated as markup or code and runs in your page with your site's power.
2. What are the three types?
Stored (saved by a visitor and shown later), reflected (echoed straight from a request), and DOM-based (inserted by your own browser-side code).
3. What is the core fix?
Keep data and code apart: escape untrusted text on output for the context it is placed in, and use safe APIs that treat values as text.
4. Why is there no single escaping function?
Each context has different special characters. HTML text, attributes, URLs, and script data each need their own encoding.
5. How do you handle a link address from a visitor?
Check its scheme against an allow-list, such as http, https, and mailto, and replace anything else. Never allow javascript: addresses.
6. What do you do if you must allow some HTML?
Sanitise it with a well-maintained library using a small allow-list of tags and attributes, or use a safe format such as Markdown through a trusted converter.
Key Takeawaysβ
- XSS is untrusted text becoming code. Keep data and code apart.
- Escape on output, for the context. HTML, attribute, URL, and script data differ.
- Prefer
textContentandcreateElementtoinnerHTML. - Allow-list URL schemes and any HTML you permit.
- Use a maintained sanitiser, never your own.
- Add layers: a Content Security Policy and
HttpOnlycookies. - Test your own pages with harmless markers, and only your own.
Next up: iFrame Security, where you will learn how to embed other pages without giving them the keys.