URI Sanitization Utility for Micromark

2.0.1 · active · verified Sun Apr 19

micromark-util-sanitize-uri is a focused utility package within the unified collective's micromark ecosystem, designed to safely normalize and sanitize URIs. It currently operates at version 2.0.1. The package encodes unsafe characters using percent-encoding, skips already encoded sequences, and can further sanitize URIs by validating against a regex of allowed protocols, effectively neutralizing potentially dangerous `javascript:` schemes. This utility is crucial for developers building custom micromark extensions or processing user-generated content, ensuring that URLs rendered in HTML are free from XSS vulnerabilities. As part of the broader micromark project, it follows the unified collective's release cadence, with major versions tied to Node.js LTS support, ensuring compatibility with Node.js 16+ for its current v2 release.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates `sanitizeUri` with protocol filtering and `normalizeUri` for encoding special characters, showing how to make URLs safe for embedding.

import { sanitizeUri, normalizeUri } from 'micromark-util-sanitize-uri';

// Sanitize a URI, disallowing javascript: protocols
const safeUrl = sanitizeUri('javascript:alert(1)', /^https?$/i);
console.log(`Sanitized dangerous URL: '${safeUrl}'`); // Expected: ''

// Normalize a URI, encoding unsafe characters
const encodedUrl = normalizeUri('https://example.com/a&b space👍');
console.log(`Normalized URL with special chars: '${encodedUrl}'`); // Expected: 'https://example.com/a&b%20space%F0%9F%91%8D'

// Sanitize a relative URL, still allowing it through if protocol pattern is specific
const relativeUrl = sanitizeUri('./image.png', /^https?$/i);
console.log(`Sanitized relative URL with http/s pattern: '${relativeUrl}'`); // Expected: './image.png'

// An example of a valid URL passing through the sanitizer
const validUrl = sanitizeUri('https://example.com/path', /^https?$/i);
console.log(`Sanitized valid URL: '${validUrl}'`); // Expected: 'https://example.com/path'

view raw JSON →