react-secure-html
v0.1.1
Published
React SafeHtml component library
Maintainers
Readme
react-secure-html
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-htmlPeer 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:anddata: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: <script>alert('xss')</script>
// 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 formattingp,br,span- Structureclass,idattributes 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 devAvailable 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 checkingTesting
# 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
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Run tests:
pnpm test - Commit:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- DOMPurify - For providing excellent HTML sanitization
- React - For the amazing framework
- TypeScript - For type safety
📞 Support
Made with ❤️ by Ramon Xavier
