In XSS Basics, one comment containing <script> made a pop-up appear in every reader's browser. The question now: how can that comment still appear with its text whole, but never run as code?
The answer is one rule: data from a user is turned into text right where it is placed. Picture a newspaper quoting someone. The quote goes inside quotation marks, so readers know those are someone else's words, not the paper's own statement. Escaping works like those quotation marks, but for the browser: the data from a user is the quote, and the browser is the reader. With escaping, < is written <. The browser shows a < sign but doesn't open a tag.
Escaping HTML: five characters
Five characters have a special meaning in HTML. Escaping replaces them with entities, codes the browser reads as ordinary characters:
| Character | Becomes |
|---|---|
& |
& |
< |
< |
> |
> |
" |
" |
' |
' |
In the exercise, you finish the escape function sanitizeHTML. The complete version:
function sanitizeHTML(input) {
return input
.replace(/&/g, "&") // must come first
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
console.log(sanitizeHTML("<script>alert(1)</script>")); // <script>alert(1)</script>
console.log(sanitizeHTML('Hi "Budi"')); // Hi "Budi"
console.log(sanitizeHTML("a & b < c")); // a & b < c
Before you read on, guess: if the order is flipped (< replaced first, then &), what does a & b < c become?
- It's named
sanitizeHTML, but what it does is escape: every character stays, only written as an entity. The browser shows<script>alert(1)</script>as text. - In the regex
/&/g, thegflag (a setting letter at the end of the regex) makes every&get replaced, not just the first. &must be replaced first. If<goes first,<becomes<. Then the&step also replaces the&of<, so the result isa & b &lt; c. The page shows the text<, not a<sign. That's the answer to the guess.'can be written'or', they mean the same.
It depends on where it goes
The right defence depends on where the data is placed. The Lab uses one template (a piece of HTML with an empty spot ... for the user's data) for each place:
| Place | Template | Defence | a & b < c becomes |
|---|---|---|---|
| Element content | <p>Comment: ...</p> |
sanitizeHTML |
a & b < c |
| Attribute value | <input value="..."> |
sanitizeHTML, attributes always quoted |
a & b < c |
| URL | <a href="/search?q=..."> |
encodeURIComponent |
a%20%26%20b%20%3C%20c |
- In an attribute, the most dangerous character is
", because"ends the attribute's value. Without escaping,<input value="Hi "Budi"">breaks off afterHi. The rest,budi"", is read as a new attribute (the browser writes attribute names in lower case). With", the value stays whole:Hi "Budi". - In a URL,
&separates parameters (the name and value pairs after?), and spaces aren't allowed. Without encoding, the server readsqas justa.encodeURIComponentturns&into%26and a space into%20. - When the whole URL comes from a user, such as a website field on a profile, also check how it starts: it must be
https:orhttp:. That way ajavascript:link (a link that runs code when clicked) is refused.
Let the template escape
Modern template engines (tools that build HTML from a template and data) escape automatically. What you need to recognise are the shortcuts that turn that escaping off. Here is how escaping and its shortcuts look in plain PHP, in Blade (Laravel's template engine), and in React:
// Plain PHP: escape it yourself
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
{{-- Blade --}}
<p>{{ $comment->body }}</p> {{-- safe: escaped --}}
<p>{!! $comment->body !!}</p> {{-- dangerous: printed raw --}}
// React: {name} is escaped automatically
<h1>Hi, {name}</h1>
// dangerouslySetInnerHTML skips escaping: never for user text
<div dangerouslySetInnerHTML={{ __html: userInput }} />
htmlspecialcharsturns& < > " 'into entities, exactly likesanitizeHTML.ENT_QUOTESmakes sure both kinds of quotes are converted. It has been the default since PHP 8.1, but writing it is still a good habit.'UTF-8'names the text's encoding.- Blade's
{{ }}callshtmlspecialcharsautomatically, so it's safe. - Blade's
{!! !!}prints raw, with no escaping. Ifbodyholds a script, your site has XSS. Use{{ }}, or clean it first with a sanitizer (next section) when the content really is HTML.
When you really need HTML: a sanitizer
Sometimes a comment may contain bold and italic text. Escaping would show <b> as text, not as bold text. So here you use an allowlist sanitizer: a library that cleans HTML with a list of allowed tags and drops everything else. Here is an example with DOMPurify:
import DOMPurify from "dompurify";
const comment = "<b>Budi</b> <img src=x onerror=alert(1)>";
const clean = DOMPurify.sanitize(comment, { ALLOWED_TAGS: ["b", "i"], ALLOWED_ATTR: [] });
console.log(JSON.stringify(clean)); // "<b>Budi</b> "
box.innerHTML = clean;
- An allowlist (what is allowed, also called a whitelist) is safer than a blocklist (what is forbidden, also called a blacklist): a tag that isn't on the list, including one you don't know about, is dropped automatically.
ALLOWED_ATTR: []drops every attribute,onerrorincluded.<img>isn't on the list, so it disappears entirely.JSON.stringifyis there so you can see the space left at the end.- Use a maintained library such as DOMPurify. Don't write your own regex to strip tags.
💡 CSP: the last safety net
Content Security Policy (CSP) is a response header that tells the browser which scripts may run:
Content-Security-Policy: script-src 'self' 'nonce-abc123'
'self': JavaScript files from your own domain may run.'nonce-abc123': an inline script (a script written directly inside the HTML) with the attributenonce="abc123"may run. The nonce is a random value made new in every response.- Other inline scripts and event handlers like
onerrorare refused. So if an escape is missed somewhere, the attacker's script still doesn't run. - Avoid
'unsafe-inline': without a nonce, it allows every inline script again.
CSP is a safety net, not a replacement for escaping. The Content Security Policy lesson covers it in detail.
⚠️ Escaping in the wrong order or the wrong place
¬ replaced first. The result is escaped twice (&lt;), and the page shows the entity code instead of the sign.- One defence for every place. A URL needs
encodeURIComponent. In an unquoted attribute, one space already ends the value and starts a new attribute, so always use quotes. {!! !!}ordangerouslySetInnerHTMLfor user data. Both turn off the built-in escaping.- Escaping when saving, then displaying raw. The same data can appear somewhere else (JSON, an attribute, an email), and each place needs its own defence. Escape when displaying, to fit the place.
TL;DR: Turn user data into text right where it is placed. In HTML, escape five characters with entities (codes the browser shows as ordinary characters): & to & (first), < to <, > to >, " to ", ' to '. In attributes, always use quotes; in URLs, use encodeURIComponent. PHP: htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8'). In Blade (Laravel's templates), {{ }} escapes automatically, and {!! !!} prints raw. When user data really may contain HTML, use an allowlist sanitizer such as DOMPurify, which lets only the tags on its list through. CSP (a header that limits which scripts may run) is the last safety net, not a replacement for escaping.
⚡ Five characters, & first
Write:
return input
.replace(/&/g, "&") // must come first
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
Guess first: if < is replaced before &, what does a & b < c become?
a & b &lt; c. < has already become <, and then the & of < gets replaced too. The page shows the text <, not a < sign.
Meaning: input is the text from a user. Escaping writes HTML's five special characters as entities (codes the browser shows as ordinary characters), so the browser doesn't open a tag. & is replaced first because every entity starts with &.
⚡ The defence depends on the place
Meaning: In element content, escape those five characters. In an attribute value, escape too, and always use quotes. In a URL, use encodeURIComponent, which turns & into %26 and a space into %20.
⚡ Let the template escape
Write:
<p>{{ $comment->body }}</p> {{-- safe: escaped --}}
<p>{!! $comment->body !!}</p> {{-- dangerous: printed raw --}}
Meaning: $comment->body is the comment text from a user. In Blade (Laravel's template engine), {{ }} calls htmlspecialchars, PHP's escape function, automatically. {!! !!}, like React's dangerouslySetInnerHTML, prints raw with no escaping, so never use them for user data.
⚡ When HTML really is allowed
Meaning: When a comment may contain tags like <b>, use an allowlist sanitizer such as DOMPurify. It lets only the tags on its list through and drops the rest. CSP (a header that tells the browser which scripts may run) is the last safety net, not a replacement for escaping.