Security

XSS in TypeScript React: How to Prevent It

React's JSX auto-escapes string values by default. But developers can bypass this with dangerouslySetInnerHTML, creating XSS vulnerabilities even in TypeScript apps.


❌ Vulnerable dangerouslySetInnerHTML

interface Props { userBio: string; }

function UserProfile({ userBio }: Props) {
  return (
    <div dangerouslySetInnerHTML={{ __html: userBio }} />
  );
  // If userBio contains <script>, it executes!

✅ Safe with DOMPurify

import DOMPurify from 'dompurify';

function UserProfile({ userBio }: Props) {
  const sanitizedBio = DOMPurify.sanitize(userBio, {
    ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong'],
    ALLOWED_ATTR: []
  });
  return <div dangerouslySetInnerHTML={{ __html: sanitizedBio }} />;
}
💡

Pro tip: Prefer rendering user content as React components (e.g. react-markdown) rather than raw HTML. This provides XSS immunity by design.

Paste this code into LearnCodeGuide

Detect TypeScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze TypeScript Code →

Related Guides

Javascript XssTypescript Sql InjectionTypescript Hardcoded Secrets