Skip to content

ramonxm/react-secure-html

react-secure-html

npm version npm downloads bundle size license

TypeScript React DOMPurify

Security Code Quality Test Coverage

A secure, performant React component library for rendering sanitized HTML with DOMPurify integration

πŸ“– Documentation β€’ πŸš€ Quick Start β€’ πŸ”’ Security β€’ 🀝 Contributing β€’ πŸ“„ License


🎯 Why react-secure-html?

  • πŸ”’ Security First: Built with DOMPurify, the industry standard for HTML sanitization
  • ⚑ Performance: Optimized bundle size (~2.5KB gzipped) with tree-shaking support
  • 🎨 Developer Experience: Full TypeScript support with excellent IntelliSense
  • 🌐 Universal: Works in React 18+, Next.js, Remix, and all modern React frameworks
  • πŸ›‘οΈ XSS Protection: Comprehensive protection against malicious HTML content
  • πŸ“± SSR Ready: Server-side rendering support with fallbacks

πŸ“¦ Installation

# npm
npm install react-secure-html

# pnpm (recommended)
pnpm add react-secure-html

# yarn
yarn add react-secure-html

Peer Dependencies

{
  "react": "^18 || ^19",
  "react-dom": "^18 || ^19"
}

πŸš€ Quick Start

Basic Usage

import { SafeHTML } from 'react-secure-html';

function App() {
  return <SafeHTML content="<p>Hello <strong>World</strong>!</p>" allowHTML />;
}

With Custom Styling

<SafeHTML content={userContent} allowHTML tag="article" className="prose prose-lg max-w-none" />

Using the Hook

import { useSanitize } from 'react-secure-html';

function MyComponent() {
  const { sanitize, sanitizeHTML, escape } = useSanitize();

  const safeText = sanitize(userInput, false); // Escapes HTML
  const safeHTML = sanitizeHTML(userHTML); // Sanitizes with DOMPurify

  return <div dangerouslySetInnerHTML={{ __html: safeHTML }} />;
}

πŸ“– Documentation

SafeHTML Component

Prop Type Default Description
content string - Raw HTML or text content to render
allowHTML boolean false Whether to allow HTML tags (sanitized)
className string - CSS class name to apply
tag keyof React.JSX.IntrinsicElements 'div' HTML tag to render as

useSanitize Hook

Returns an object with sanitization utilities:

const {
  sanitize, // (input: string, allowHTML?: boolean) => string
  sanitizeHTML, // (html: string, options?: Config) => string
  escape, // (text: string) => string
  sanitizeUrl, // (url: string) => string
} = useSanitize();

Direct Utilities

import { sanitizeHTML, escapeHTML, sanitizeInput, sanitizeURL } from 'react-secure-html';

// Sanitize HTML with DOMPurify
const cleanHTML = sanitizeHTML('<p>Safe content</p>');

// Escape HTML entities
const escapedText = escapeHTML('<script>alert("xss")</script>');

// Sanitize user input
const safeInput = sanitizeInput(userInput, false);

// Sanitize URLs
const safeUrl = sanitizeURL('https://example.com');

πŸ”’ Security

This library provides multiple layers of security:

XSS Protection

  • DOMPurify Integration: Uses the industry-standard DOMPurify library
  • HTML Entity Escaping: Converts dangerous characters to safe entities
  • URL Sanitization: Prevents javascript: and data: URL schemes
  • Tag Filtering: Only allows safe HTML tags by default

Safe Defaults

// By default, HTML is escaped (safe)
<SafeHTML content="<script>alert('xss')</script>" />
// Renders: &lt;script&gt;alert('xss')&lt;/script&gt;

// Only when explicitly allowed, HTML is sanitized
<SafeHTML content="<script>alert('xss')</script>" allowHTML />
// Renders: (script tag removed)

Allowed HTML Tags (when allowHTML=true)

  • b, i, em, strong - Text formatting
  • p, br, span - Structure
  • class, id attributes only

🌟 Examples

Blog Post Renderer

function BlogPost({ content }: { content: string }) {
  return (
    <SafeHTML content={content} allowHTML tag="article" className="prose prose-lg max-w-none" />
  );
}

User Comments

function Comment({ text }: { text: string }) {
  return <SafeHTML content={text} allowHTML tag="div" className="comment-content" />;
}

Rich Text Preview

function RichTextPreview({ content }: { content: string }) {
  const { sanitizeHTML } = useSanitize();

  return (
    <div
      className="preview"
      dangerouslySetInnerHTML={{
        __html: sanitizeHTML(content, {
          ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a'],
          ALLOWED_ATTR: ['href', 'class'],
        }),
      }}
    />
  );
}

Email Template Renderer

function EmailTemplate({ html }: { html: string }) {
  return <SafeHTML content={html} allowHTML tag="div" className="email-template" />;
}

πŸ› οΈ Development

Prerequisites

  • Node.js 18+
  • pnpm (recommended) or npm

Setup

# Clone the repository
git clone https://github.com/ramonxm/react-secure-html.git
cd sanitize-html

# Install dependencies
pnpm install

# Start development
pnpm dev

Available Scripts

pnpm dev          # Watch mode for development
pnpm build        # Build for production
pnpm test         # Run tests
pnpm test:watch   # Run tests in watch mode
pnpm test:ui      # Run tests with UI
pnpm lint         # Lint code
pnpm lint:fix     # Fix linting issues
pnpm format       # Format code
pnpm type-check   # TypeScript type checking

Testing

# Run all tests
pnpm test

# Run tests with coverage
pnpm test --coverage

# Run tests in watch mode
pnpm test:watch

πŸ“Š Performance

  • Bundle Size: ~2.5KB gzipped
  • Tree Shaking: Full support for unused code elimination
  • Runtime Performance: Optimized with React.useMemo and useCallback
  • Memory Efficient: No memory leaks, proper cleanup

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Quick Contribution Guide

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: pnpm test
  5. Commit: git commit -m 'Add amazing feature'
  6. Push: git push origin feature/amazing-feature
  7. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ“ž Support


About

πŸ”’ A simple, lightweight, and type-safe security React Component for HTML content.

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published