Front-End Security: XSS, Safe Rendering and Third-Party Code
Stop the attacks that run in your users' browsers: cross-site scripting and how to avoid it, safe DOM APIs, dangerous URLs, Content Security Policy, third-party scripts and supply-chain risk, where (not) to keep tokens, and clickjacking. Practise by fixing a vulnerable comment list.
1. The browser runs whatever you hand it
Your page runs in the visitor’s browser, with their cookies, their signed-in session and their trust. If an attacker can get their script to run on your page, it can act as the user: read what they see, send requests as them, steal tokens, change what the page shows. That attack is cross-site scripting (XSS), and it is still one of the most common web vulnerabilities.
XSS happens when untrusted data is treated as code. The data can come from a comment form, a profile name, a URL parameter, an API response, a file name, or a third-party widget.
| Type | How it arrives |
|---|---|
| Stored | Saved on the server (a comment, a username) and shown to other users later |
| Reflected | Part of the request (a search term in the URL) echoed back into the page |
| DOM-based | Your own JavaScript reads something (like location.hash) and writes it into the page unsafely |
2. Safe and unsafe DOM APIs
// DANGEROUS: the string is parsed as HTML and any script handlers run
el.innerHTML = userText;
el.outerHTML = userText;
el.insertAdjacentHTML('beforeend', userText);
document.write(userText);
eval(userText); new Function(userText); setTimeout(userText); // string forms execute code
// SAFE: the string is only ever text
el.textContent = userText;
el.setAttribute('title', userText); // fine for ordinary attributes
const a = document.createElement('a'); a.textContent = name; a.href = safeUrl(url);
Most XSS is a single innerHTML that was “just easier”. A template literal that builds HTML from data (`<li>${name}</li>`) assigned to innerHTML is just as unsafe.
Frameworks escape by default (React, Vue, Svelte, Angular, Astro templates). Be suspicious of the escape hatches: dangerouslySetInnerHTML, v-html, {@html ...}, [innerHTML], set:html. Each one needs a reason and a sanitiser.
If you must show user-supplied HTML (a rich-text comment), run it through a well-maintained sanitiser such as DOMPurify with a strict allow-list, never a home-made regular expression. There is also the built-in Trusted Types feature, which makes the browser refuse unsanitised strings in dangerous APIs.
3. URLs are code too
Attributes that take URLs (href, src, action, formaction) accept javascript: URLs, which run script when clicked:
<a href="javascript:stealSession()">My website</a>
Validate the scheme of any URL a user provides, and allow only what you need:
function safeUrl(input) {
try {
const u = new URL(input, location.origin);
return ['http:', 'https:'].includes(u.protocol) ? u.href : '#';
} catch {
return '#';
}
}
Also: add rel="noopener noreferrer" to target="_blank" links (modern browsers imply noopener, but it is good practice), and encode values placed into URLs with encodeURIComponent.
4. Content Security Policy
A CSP is an HTTP response header that tells the browser what the page may load and run. It is defence in depth: if an injection slips through, a good policy can stop the injected script from running.
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-r4nd0m';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
base-uri 'self';
object-src 'none'
script-src 'self'allows scripts only from your own origin. Avoid'unsafe-inline'and'unsafe-eval'for scripts: they remove most of the protection. Use nonces or hashes for the inline scripts you need.frame-ancestorscontrols who may embed your page (anti-clickjacking, replacingX-Frame-Options).- Roll out with
Content-Security-Policy-Report-Onlyfirst to see what would break.
5. Third-party code is your code
Every analytics snippet, chat widget, ad script and CDN library runs with the same power as your own JavaScript. A compromised provider becomes your breach.
- Add as few third-party scripts as you can, and load them with
asyncordefer. - Use Subresource Integrity for files loaded from a CDN, so a changed file is refused:
<script src="https://cdn.example/lib.min.js" integrity="sha384-..." crossorigin="anonymous"></script>
- Pin exact versions and check packages before installing them. Be careful of look-alike names (“typosquatting”), abandoned packages and install scripts. Run
npm audit, keep a lock file, and review updates. - Put untrusted widgets in a sandboxed iframe (
sandboxattribute) so they cannot reach your page.
6. Where to keep tokens and secrets
- Nothing in the front end is secret. Source, bundled code,
localStorage, network requests and.envvalues used by client code are all readable. Never embed private API keys or passwords. Call your server, which holds them. - Session tokens in
localStoragecan be stolen by any XSS. Prefer HttpOnly, Secure, SameSite cookies, which JavaScript cannot read. If you must hold a token in memory, keep it short-lived. - Do not put sensitive data in URLs (they end up in history, logs and
Refererheaders). - Use
autocompletecorrectly, andtype="password"fields for secrets.
7. Other front-end attacks to know
- Clickjacking: your page is framed invisibly and users click things they cannot see. Defend with
frame-ancestors 'none'(or'self'). - CSRF: a malicious site makes the user’s browser send an authenticated request. Defend with
SameSitecookies and CSRF tokens on state-changing requests (a server task, but you build the forms and requests). - Open redirects:
?next=parameters that send users to any site. Allow only relative paths. postMessageandwindow.open: always checkevent.originand the message shape.- Prototype pollution and unsafe merging of untrusted JSON into objects: validate shapes, and avoid
Object.assignor deep-merge of user data into live objects.
8. A checklist for every feature
- Where does each piece of data come from? Assume anything outside your own code is hostile.
- Is it inserted as text (safe) or as HTML/URL/code (needs escaping, validation or sanitising)?
- Is the user’s session protected from script (HttpOnly cookie)?
- Is there a CSP and are third-party scripts minimised and pinned?
- Does the server also validate, since the front end can be bypassed?
9. Your turn: fix the comment list
This page renders comments with innerHTML. The second comment contains an attack: an image with an onerror handler and a javascript: link. Fix render() so that:
- each comment is built with DOM methods and
textContent(noinnerHTML), - user text is shown exactly as typed (the attacker’s markup appears as visible text),
- the website link uses your
safeUrl()function, so thejavascript:URL becomes#andhttps:links are kept.
Your tasks
- ○Three comments are rendered
- ○The injected <img> was not created
- ○The attacker's script did not run (no 'hacked' flag)
- ○The attacker's markup is shown as visible text
- ○A name containing <b> is shown as text, not turned into bold markup
- ○No link uses a javascript: URL; the dangerous one became #
- ○The normal https links are kept
10. What you learned
XSS is untrusted data treated as code, so insert data as text, validate URL schemes, sanitise any HTML with a proven library, and add a Content Security Policy as a second line of defence. Treat third-party scripts as part of your code, keep secrets and session tokens out of reach of JavaScript, and remember the server must validate too. Next: making pages fast.
🧪 Want to practise this on your own computer? See how to set up your lab →