XSS and open redirects: when data becomes markup or a destination
Cross-site scripting happens when one party's data is interpreted as HTML or JavaScript by another party's browser.
Remember: Render untrusted data as text. Where HTML is required, sanitise with an allowlist and back it with a Content Security Policy.
Stored XSS sits in the database and runs for every viewer. Reflected XSS comes back in the response. DOM-based XSS never reaches the server at all: the browser reads a value from the URL and writes it into the page.
- Sinks to look for: dangerouslySetInnerHTML, innerHTML, outerHTML, document.write, eval, new Function.
- href or src built from input, which allows javascript: URLs.
- Template features that turn escaping off: triple braces, a safe filter, raw output.
<div dangerouslySetInnerHTML={{ __html: note.body }} />
<div className="note-body">{note.body}</div>
When you need formatting
Convert markdown to a safe syntax tree, or sanitise HTML on the server with an allowlist of tags and attributes. Add a Content Security Policy so that a missed injection cannot run inline scripts.
Open redirects
A redirect parameter lets an attacker send victims from a trusted domain to a phishing page. Accept only internal paths that start with a single slash.
The URL fragment (the part after #) is never sent to the server, so logs and firewalls do not see it. Treat location.hash in client code as untrusted input.
Questions to ask yourself
- Where does this value come from, and who wrote it?
- Which sink receives it: HTML, a URL, or a script?
- Is escaping on by default in this template or component?
Practise this
- Shared notes with HTML · Next.js / React
- Receipt reference from the URL hash · Injection & input
- Redirect after login · Next.js / React
- PHP profile page echoing request values · Injection & input