Security10 min read

How to Prevent XSS in AI-Built and Vibe-Coded SaaS Apps

XSS is back in React apps. AI code generators reintroduce it via dangerouslySetInnerHTML and unsanitized markdown. Here's how to find and fix it before launch.

Cross-site scripting (XSS) is the vulnerability that React was supposed to solve — and mostly did, by escaping user-controlled values in JSX by default. AI coding tools like Lovable, Bolt, Cursor, and v0 reintroduce XSS in predictable ways: by generating dangerouslySetInnerHTML without sanitization, by wiring up markdown renderers that output raw HTML into the DOM, and by using plain JavaScript template strings to build DOM content. The result is that vibe-coded SaaS apps shipped in 2026 carry XSS vulnerabilities in a framework that was designed to prevent them.

The impact is not abstract. XSS enables session hijacking, account takeover, and stored script injection in multi-tenant SaaS — where one user's injected payload fires inside every other user's browser whenever they view the affected content. In a SaaS application with a persistent markdown editor, comment section, or user profile field, a stored XSS vulnerability is critical: it's not about stealing a cookie from one unlucky user; it's about executing arbitrary JavaScript in every session that loads the infected record. HttpOnly cookies don't prevent this — the injected script can still make authenticated API requests as the victim.

This guide covers every XSS entry point that AI-generated and vibe-coded SaaS apps introduce, how to find them in your codebase in under an hour, how to fix each type, and how to add a Content Security Policy that reduces the blast radius of any XSS that gets through. For the broader pre-launch security picture, see the SaaS pre-launch security checklist.

Why React Doesn't Automatically Protect You From XSS

React escapes string values when you render them in JSX using curly braces: {userContent} renders the string as text, not as HTML. A string containing a script tag renders as the literal characters, not as an executable script. This protection is why React eliminated an entire class of XSS vulnerabilities that plagued earlier JavaScript frameworks — but it has four specific bypass routes that AI-generated code uses regularly.

  • →dangerouslySetInnerHTML: React's explicit escape hatch for rendering raw HTML. The name is a warning, but AI code generators use it without hesitation when a component needs to render HTML content. Any value passed to __html that contains user-controlled input is an XSS vulnerability.
  • →Direct DOM manipulation in useEffect and event handlers: Code that calls element.innerHTML = someValue or element.insertAdjacentHTML() bypasses React's escaping entirely. AI tools generate this pattern when porting a plain JavaScript snippet or when they think React's re-rendering cycle is too slow for a particular use case.
  • →Third-party markdown and rich text renderers: Libraries like marked and showdown render markdown to HTML by default and do not sanitize that output. When passed user-supplied markdown, the rendered HTML may contain script-executing payloads. This is one of the most common XSS sources in AI-generated SaaS apps that have comment or note features.
  • →Template literals passed to eval, setTimeout, or the Function constructor: AI-generated utility code occasionally passes user-controlled strings to JavaScript's dynamic evaluation mechanisms. This is an instant XSS — and in some environments an RCE — vulnerability and must be treated as critical regardless of how the input appears to be validated.

dangerouslySetInnerHTML: The Primary XSS Source in AI-Generated React Apps

The dangerouslySetInnerHTML prop is the most common XSS entry point in vibe-coded React applications. AI coding tools generate it in several recurring patterns: rendering HTML content returned from an API or CMS, displaying formatted notification messages, rendering user bios or profile descriptions, and implementing a simple preview feature for content the user is writing. Each is a potential XSS vector if the value is not sanitized before it reaches the prop.

  • →Find every instance in your codebase: run grep -rn 'dangerouslySetInnerHTML' in the project root and read each result. For each one, trace the source of the __html value. If it originates from a database field, an API response body, a URL parameter, or any value a user can control, it needs sanitization before use.
  • →The correct fix for most cases is DOMPurify: import DOMPurify from 'dompurify' and pass the value through DOMPurify.sanitize(value) before assigning it to __html. DOMPurify parses the HTML, removes unsafe elements and attributes (script tags, onerror handlers, javascript: href values), and returns a sanitized string. It is maintained, widely audited, and handles edge cases that manual approaches miss.
  • →Configure DOMPurify for your content type. For profile descriptions and comments where you want basic formatting but not links, use DOMPurify.sanitize(value, { ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p', 'br'], ALLOWED_ATTR: [] }). User-controlled fields should always use the most restrictive configuration your use case supports.
  • →Consider whether dangerouslySetInnerHTML is necessary at all. If the content you are rendering is plain text that uses HTML only because a CMS or AI tool generated it that way, strip the HTML and render as text. Rendering plain text is always safer than sanitizing HTML because it eliminates the HTML rendering surface entirely.

Markdown Renderers and Rich Text Editors: The Hidden XSS Surface

Markdown rendering is the XSS surface that catches vibe-coded SaaS teams off guard most often, because markdown feels like a safe format — it's structured text, not HTML. But every markdown renderer converts the markdown to HTML before displaying it, and that conversion process is where XSS enters if the renderer isn't configured carefully.

  • →The marked library renders markdown to HTML and passes raw HTML through by default. If a user writes an img tag with an onerror event handler in a markdown field, marked outputs that tag verbatim. The fix is to run DOMPurify.sanitize() on the output of marked(), or switch to a renderer that sanitizes by default.
  • →react-markdown is safer than marked for React applications because it renders to React elements rather than raw HTML. By default, it disables raw HTML in the markdown source. If you or an AI tool has enabled it with the rehypePlugins={[rehypeRaw]} option, raw HTML tags in user-supplied markdown will render directly — re-enabling the XSS risk. Remove rehypeRaw unless you have an explicit sanitization pipeline after it, using rehype-sanitize.
  • →Rich text editors like Quill, TipTap, and Slate all store their content as HTML or a JSON schema that serializes to HTML. The XSS risk appears when you display that content: loading the stored HTML back into an innerHTML-based renderer without sanitizing it first. Store the sanitized version, or sanitize at display time — but do one of the two, not neither.
  • →Third-party embedded content (video embeds, code snippets) is a source of XSS in SaaS apps that allow rich user content. An allowlist approach — where only specific embed types from specific domains are permitted, and all other HTML is stripped — is safer than trying to sanitize arbitrary HTML from user input.

DOM-Based XSS in AI-Built JavaScript

DOM-based XSS is distinct from reflected and stored XSS because the attack doesn't require a server-side vulnerability. The payload never reaches your server — it flows entirely from a source (the URL hash, a query parameter, localStorage, postMessage data) to a sink (innerHTML, document.write, eval) in the client-side JavaScript. AI coding tools generate DOM-based XSS when they build client-side routing, URL parsing, or component initialization logic using direct DOM manipulation.

  • →URL-based sources are the most common DOM XSS entry point: location.hash, location.search, and new URLSearchParams(location.search).get('param') feed values that an attacker can control directly by crafting a link. Any code that takes a URL parameter and writes it to innerHTML or uses it in a template literal passed to insertAdjacentHTML is DOM-based XSS.
  • →postMessage handlers are a rising DOM XSS source in SaaS applications with iframe integrations, widget embeds, or inter-frame communication. AI-generated postMessage handlers often accept messages from any origin (by not checking event.origin) and pass the message data to DOM sinks. Always validate event.origin against an explicit allowlist and validate the message schema before using the data.
  • →localStorage and sessionStorage values can be sources of DOM XSS if an attacker can influence what gets stored there. Cross-site script inclusion, prototype pollution, and supply chain attacks can plant payloads in storage that execute when your code reads them into a DOM sink. Treat storage reads with the same validation as external API reads.
  • →The grep-based audit for DOM XSS: search for .innerHTML, .outerHTML, insertAdjacentHTML, document.write, and eval with a string argument across all TypeScript and JavaScript files. For each hit, trace the data flowing into it back to its origin. If the origin is user-controlled — URL, storage, database field, or postMessage — the code has a DOM XSS vulnerability.

Stored XSS in Multi-Tenant SaaS: Why the Stakes Are Higher

In a multi-tenant SaaS application, stored XSS has a blast radius that scales with your user base. A payload injected into a shared record — a team comment, a project description, a workspace name, an admin notification — executes inside every user's browser session that loads that record. One injection can steal session tokens from every user in a workspace, modify account settings across the organization, or silently exfiltrate data from every document the affected users have access to. Authorization vulnerabilities in multi-tenant SaaS amplify the impact further: if an attacker can inject into a resource visible to all tenants, the attack crosses tenant isolation boundaries.

  • →Sanitize at write time, not only at read time. When a user submits content, sanitize it before persisting it to the database. This prevents the payload from being stored and fired for every subsequent reader. Sanitizing only at display time means every read path must correctly sanitize — a missed code path, a new API endpoint, or a data export feature can bypass display-time sanitization and return the raw payload.
  • →Profile fields, workspace names, and invitation messages are the input fields most likely to store a payload that fires for other users. These are the fields that appear in notifications, audit logs, shared dashboards, and email templates. AI-generated apps that add these features often include the data directly in the template without sanitization.
  • →Test for stored XSS by submitting a benign but detectable payload to every user-controlled input field that other users can view. After submitting, load the page as a different user and check whether the payload rendered in the DOM. If the browser executed any part of the input, the field is vulnerable to stored XSS.
  • →API responses that include user-controlled content are a stored XSS vector in applications that render API data into innerHTML. This applies to webhooks that display external content, integrations that pull in contact names or message text from third-party APIs, and any place where data from outside your control enters your rendering pipeline.

Content Security Policy: Limiting XSS Blast Radius

A Content Security Policy (CSP) doesn't prevent XSS from reaching your DOM — it restricts what an injected script can do. With a strict CSP in place, a payload that executes can't load external resources, can't send data to attacker-controlled servers, and in some configurations can't execute inline scripts at all. CSP is not a substitute for sanitization, but it is a critical defense-in-depth layer that reduces the practical impact of a vulnerability that slips through. It is also one of the checks DeployReady flags when missing — a production app without CSP headers is a configuration issue that static analysis catches before launch.

  • →Add CSP headers in Next.js via the headers() function in next.config.ts. A starting point: script-src 'self'; object-src 'none'; base-uri 'self'. This prevents loading scripts from arbitrary external domains. If you use Google Fonts, inline styles, or third-party script tags, you will need to extend this — but start restrictive and add exceptions explicitly.
  • →The unsafe-inline directive for script-src negates most of CSP's XSS protection. It allows inline script execution, which is exactly what most XSS payloads use. If your app requires inline scripts, migrate to nonce-based CSP (each server response includes a unique nonce value in both the header and the script tag) or hash-based CSP (the hash of each permitted inline script is listed in the header).
  • →The report-uri or report-to directive sends CSP violation reports to an endpoint you control. Enable this in reporting mode (Content-Security-Policy-Report-Only header) before enforcing, and monitor the violations for a few days. AI-generated code frequently loads scripts from CDNs and third-party sources that you will need to explicitly permit — the report mode surfaces these before the enforced policy blocks them.
  • →frame-ancestors 'none' in the CSP header prevents your application from being loaded in an iframe on another domain, which eliminates clickjacking as an XSS amplification vector. Add this alongside the main script-src policy. For applications that use iframes internally, use frame-ancestors with an explicit origin allowlist.

How to Audit Your Codebase for XSS in One Hour

A focused manual audit of an AI-generated React codebase for XSS takes under an hour for a medium-sized application and surfaces most vulnerabilities. The audit consists of three grep passes. For the broader context of what else breaks in AI-generated codebases, see what vibe-coded apps get wrong about authentication — XSS and broken auth often appear together in the same codebase.

  • →Pass 1 — DOM sinks: Search for dangerouslySetInnerHTML, innerHTML, outerHTML, insertAdjacentHTML, document.write, and eval across all .ts, .tsx, .js, and .jsx files. Read each result and trace the data flow. Mark each as safe (constant value, no user input) or as a finding (user-controlled input flows in without sanitization).
  • →Pass 2 — Rendering libraries: Check package.json for marked, showdown, dompurify, react-markdown, rehype-raw, quill, slate, tiptap, and lexical. For each rendering library present, check how it is configured and whether it sanitizes output. For marked and showdown, check whether DOMPurify is applied to the output. For react-markdown, check whether rehypeRaw is enabled.
  • →Pass 3 — URL sources and postMessage: Search for location.hash, location.search, URLSearchParams, and postMessage in the codebase. For each, check whether the extracted value flows to a DOM sink. Any value from these sources that reaches innerHTML or eval without sanitization is DOM-based XSS.
  • →Check CSP configuration: Look in next.config.ts for a headers() function. If there is no Content-Security-Policy header configured, that is a missing defense-in-depth finding. If there is a CSP header, check whether unsafe-inline is present in the script-src directive — if it is, the CSP provides limited XSS protection.

Frequently Asked Questions

Does React prevent XSS automatically?

React escapes string values rendered via JSX curly braces by default, which prevents the most common form of reflected XSS. It does not prevent XSS when you use dangerouslySetInnerHTML, when you manipulate the DOM directly in JavaScript via innerHTML or insertAdjacentHTML, or when you pass user-controlled values to markdown renderers that output raw HTML. AI code generators regularly produce all three patterns.

What is the safest way to render user-submitted HTML in React?

Pass the HTML through DOMPurify.sanitize() before rendering it via dangerouslySetInnerHTML. Configure DOMPurify with the minimum set of allowed tags and attributes for your use case — most user-submitted content needs at most bold, italic, links, and line breaks. If you can avoid rendering HTML at all and render plain text instead, that is always the safer choice. Never trust that content from your own database is safe if users control the input fields.

Can HttpOnly cookies prevent XSS session hijacking?

HttpOnly cookies prevent JavaScript from reading the cookie value directly via document.cookie, but they do not prevent session hijacking via XSS. An injected script can make authenticated API requests using the session cookie — the browser attaches it automatically — read the responses, and perform actions as the authenticated user without ever reading the cookie value. Treat XSS as a full session-level compromise, not just a cookie theft risk.

What is the difference between stored XSS and reflected XSS?

Stored XSS is a payload that is persisted in the application's database and fires every time any user loads the affected content. Reflected XSS is a payload embedded in a URL that fires once, only for a user who clicks a crafted link. In SaaS applications, stored XSS has a much higher impact because a single injection can affect all users who view the infected content — without requiring any further attacker action after the initial injection.

How do I add a Content Security Policy to a Next.js app?

Add a headers() function in next.config.ts that returns a Content-Security-Policy header for all routes. Start with a restrictive policy — script-src 'self'; object-src 'none'; base-uri 'self' — and use the Content-Security-Policy-Report-Only header first to identify violations without breaking anything. The report mode shows you which third-party scripts, CDN resources, and inline styles the app needs, so you can permit them explicitly before switching to enforcement mode.

How Belsoft Helps with XSS and Application Security Audits

XSS vulnerabilities in AI-generated SaaS apps rarely appear in isolation. A codebase with dangerouslySetInnerHTML without sanitization typically also has missing authentication on adjacent API routes, overly permissive CORS configuration, and user-controlled input flowing into other sinks that static analysis doesn't catch. Belsoft's security audit for SaaS and vibe-coded apps covers XSS entry points manually — tracing data flow from every user-controlled input through every rendering path — alongside the full authorization model, session handling, API security, and AI feature attack surface. We test it, document every finding, help the team fix it, and retest to verify.

For teams that want an immediate automated baseline before the manual audit, DeployReady — Belsoft's open-source security CLI — includes XSS-related static analysis checks: it identifies dangerouslySetInnerHTML usage in React components, flags innerHTML assignments in TypeScript and JavaScript files, checks for a Content Security Policy header, and scans for missing DOMPurify when rendering libraries are detected. Run it today with npx deployready in your project root. The automated scan is the starting point; a Belsoft audit adds the data flow analysis, manual testing, and AI feature review that static tools cannot do.

“React eliminated most XSS — but AI coding tools added it back. The fix takes a grep, a DOMPurify import, and a CSP header. Run the audit before launch, not after.”

Written by

Marco Silva

Security Engineer, Belsoft Solutions

Ready to partner?

Let's talk about your company.

30 minutes. No pitch. We talk through how you run today and where AI and automation would help.

Book a free audit
logo

Your AI & automation transformation partner: we audit, build, and train your team, then stay embedded as you grow.

Member ofNVIDIA Inception Program

Copyright Ⓒ 2026 BelSoft. All Rights Reserved.

BELSOFT, LDA · NIPC 517893258 · Lisbon, Portugal