package
A security-focused wrapper for react-markdown that filters URLs based on allowed prefixes
npm install harden-react-markdownGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
A wrapper for react-markdown that ensures that untrusted markdown does not contain images from and links to unexpected origins.
This is particularly important for markdown returned from LLMs in AI agents which might have been subject to prompt injection.
This package validates URL prefixes and URL origins. Prefix allow-lists can be circumvented with open redirects, so make sure to make the prefixes are specific enough to avoid such attacks.
E.g. it is more secure to allow https://example.com/images/ than it is to allow all of
https://example.com/ which may contain open redirects.
Additionally, URLs may contain path traversal like /../. This package does not resolve these.
It is your responsibility that your web server does not allow such traversal.
npm install harden-react-markdown react react-markdown
# or
yarn add harden-react-markdown react react-markdown
# or
pnpm add harden-react-markdown react react-markdownimport React from "react";
import ReactMarkdown from "react-markdown";
import hardenReactMarkdown from "harden-react-markdown";
// Create a hardened version of ReactMarkdown
const HardenedMarkdown = hardenReactMarkdown(ReactMarkdown);
function MyComponent() {
const markdown = `
# My Document
[Safe Link](https://github.com/user/repo)
[Blocked Link](https://malicious-site.com)


`;
return (
<HardenedMarkdown
defaultOrigin="https://mysite.com"
allowedLinkPrefixes={["https://github.com/", "https://docs."]}
allowedImagePrefixes={["https://via.placeholder.com/", "/"]}
>
{markdown}
</HardenedMarkdown>
);
}hardenReactMarkdown(MarkdownComponent)Creates a hardened version of any react-markdown compatible component.
MarkdownComponent: A React component that accepts Options from react-markdownA new component with enhanced security that accepts all original props plus:
defaultOrigin?: stringallowedLinkPrefixes or allowedImagePrefixes are provided"https://mysite.com"allowedLinkPrefixes?: string[][blocked]"*" to allow all URLs (disables filtering. However, javascript: and data: URLs are always disallowed)[] (blocks all links)['https://github.com/', 'https://docs.example.com/'] or ['*']allowedImagePrefixes?: string[]"*" to allow all URLs (disables filtering. However, javascript: and data: URLs are always disallowed unless allowDataImages is enabled)[] (blocks all images)['https://via.placeholder.com/', '/'] or ['*']allowDataImages?: booleantrue, allows data:image/* URLs (base64-encoded images) in image sourcesdata:image/* URLs are allowed; other data: URLs (like data:text/html) remain blocked for securitydata: URLs are never allowed in links, regardless of this settingfalse (blocks all data: URLs)trueallowedProtocols?: string[]tel:, mailto:, postman:, vscode:, slack:)"*" to allow all protocols that can be parsed as valid URLsjavascript:, data:, file:, vbscript:) are always blocked regardless of this setting[] (only allows built-in safe protocols: https:, http:, mailto:, irc:, ircs:, xmpp:, blob:)['tel:', 'postman:', 'vscode:'] or ['*']linkBlockPolicy?: BlockPolicyType"indicator" (default): Renders as plain text with [blocked] suffix and the blocked URL in a title attribute"text-only": Renders just the link text without any indicator or URL"remove": Removes the blocked link entirely from the outputimageBlockPolicy?: BlockPolicyType"indicator" (default): Renders as a placeholder span with [Image blocked: {alt text}]"text-only": Renders just the alt text (images with no alt text are removed)"remove": Removes the blocked image entirely from the outputAll other props are passed through to the wrapped markdown component.
const HardenedMarkdown = hardenReactMarkdown(ReactMarkdown);
// Blocks all external links and images by default
<HardenedMarkdown>{markdownContent}</HardenedMarkdown>;<HardenedMarkdown
defaultOrigin="https://mysite.com"
allowedLinkPrefixes={[
"https://github.com/",
"https://docs.github.com/",
"https://www.npmjs.com/",
]}
allowedImagePrefixes={[
"https://via.placeholder.com/",
"https://images.unsplash.com/",
"/", // Allow relative images
]}
>
{markdownContent}
</HardenedMarkdown><HardenedMarkdown
defaultOrigin="https://mysite.com"
allowedLinkPrefixes={["https://mysite.com/"]}
allowedImagePrefixes={["https://mysite.com/"]}
>
{`
[Relative Link](/internal-page)

`}
</HardenedMarkdown><HardenedMarkdown allowedLinkPrefixes={["*"]} allowedImagePrefixes={["*"]}>
{`
[Any Link](https://anywhere.com/link)

`}
</HardenedMarkdown>Note: Using "*" disables URL filtering entirely. Only use this when you trust the markdown source.
<HardenedMarkdown
defaultOrigin="https://mysite.com"
allowedImagePrefixes={["https://mysite.com/"]}
allowDataImages={true}
>
{`


`}
</HardenedMarkdown>Note: This is particularly useful when converting documents from formats like PDF or .docx where images are embedded as base64. Only data:image/* URLs are allowed; other data: URLs remain blocked for security.
Enable custom protocols for deep linking to applications and services:
<HardenedMarkdown allowedProtocols={["tel:", "mailto:", "postman:", "vscode:", "slack:"]}>
{`
[Call us](tel:+1234567890)
[Email support](mailto:support@example.com)
[Open in Postman](postman://open/collection)
[View in VS Code](vscode://file/path/to/file.ts)
[Join Slack](slack://channel?id=C123456)
`}
</HardenedMarkdown>Common use cases:
tel: - Phone number links that open the dialer on mobile devicesmailto: - Email links (allowed by default, but shown here for completeness)sms: - SMS/text message linkspostman:, vscode:, slack: - Deep links to desktop applicationsYou can also use the wildcard to allow any custom protocol:
<HardenedMarkdown allowedProtocols={["*"]}>
{`[Custom Protocol Link](customapp://action)`}
</HardenedMarkdown>Security Note: Even with allowedProtocols={["*"]}, dangerous protocols like javascript:, data:, file:, and vbscript: are always blocked for security. Custom protocols are safe because they trigger OS-level protocol handlers and don't execute in the browser context.
Control how blocked content is handled instead of the default [blocked] indicator:
<HardenedMarkdown
defaultOrigin="https://mysite.com"
allowedLinkPrefixes={["https://trusted.com/"]}
allowedImagePrefixes={["https://trusted.com/"]}
linkBlockPolicy="text-only" // Show link text only, no [blocked] indicator
imageBlockPolicy="remove" // Remove blocked images entirely
>
{markdownContent}
</HardenedMarkdown>Available policies: "indicator" (default), "text-only", "remove".
const CustomMarkdown = (props) => (
<div className="custom-wrapper">
<ReactMarkdown {...props} />
</div>
);
const HardenedCustomMarkdown = hardenReactMarkdown(CustomMarkdown);
<HardenedCustomMarkdown
defaultOrigin="https://mysite.com"
allowedLinkPrefixes={["https://trusted.com/"]}
>
{markdownContent}
</HardenedCustomMarkdown>;href attributes in <a> elementssrc attributes in <img> elementsdefaultOrigin../ attacks"*" prefix to disable filtering (only when markdown is trusted)Behavior is configurable per element type via linkBlockPolicy and imageBlockPolicy:
"indicator" (default): Blocked links show a [blocked] suffix; blocked images show [Image blocked: {alt}]"text-only": Outputs just the link text or image alt text with no indicator"remove": Removes blocked elements entirely from the outputjavascript:, data:, vbscript:, file: and other dangerous protocols (always, regardless of configuration)tel:, postman:, vscode:) with explicit opt-in via allowedProtocolsFull TypeScript support with strict type checking:
// Type-safe component creation
const HardenedMarkdown = hardenReactMarkdown(ReactMarkdown);
// Inferred prop types include both react-markdown Options and security options
type Props = Parameters<typeof HardenedMarkdown>[0];
// Works with custom markdown components
const CustomMarkdown = (props: Options & { customProp?: string }) => (
<ReactMarkdown {...props} />
);
const HardenedCustom = hardenReactMarkdown(CustomMarkdown);
// Props now include customProp + security optionsThe package includes comprehensive tests covering:
Run tests:
npm testgit checkout -b feature/amazing-feature)git commit -m 'Add some amazing feature')git push origin feature/amazing-feature)MIT License - see the LICENSE file for details.
If you discover a security vulnerability, please send an e-mail to security@vercel.com.
Estimated unpacked size across 20 packages.
1.0 MB
Includes dependencies.