Micromark HTML Character Encoder
micromark-util-encode is a focused utility package within the micromark ecosystem, designed specifically for encoding dangerous HTML characters to ensure text is safe for embedding in HTML documents. Its current stable version is 2.0.1, part of the 2.x release line which maintains compatibility with Node.js 16 and higher. As a component of the unified collective, it follows a pragmatic release cadence often aligned with major micromark and Node.js version updates. This package differentiates itself by providing a robust, performant, and standards-compliant algorithm for HTML escaping, specifically tailored for the needs of markdown processors and related text transformation tools, where correctness and minimal overhead are critical. It is fully typed with TypeScript, ensuring good developer experience for static analysis and type safety.
Common errors
-
ERR_REQUIRE_ESM
cause Attempting to `require()` an ESM-only package in a CommonJS context.fixChange `const { encode } = require('micromark-util-encode')` to `import { encode } from 'micromark-util-encode'` and ensure your project is configured for ES modules. -
TypeError: encode is not a function
cause Trying to import `encode` as a default import when it is a named export.fixEnsure you are using named imports: `import { encode } from 'micromark-util-encode'`.
Warnings
- breaking Version 2.x of `micromark-util-encode` is ESM-only. Direct `require()` calls for this package will result in an error.
- breaking Version 2.x of `micromark-util-encode` officially supports Node.js 16 and higher. Older Node.js versions are not guaranteed to work and may encounter runtime errors.
- gotcha The `encode` function specifically targets HTML characters (<, >, &, ", '). It does not perform full URL encoding or sanitize other potentially unsafe content like CSS injections or script execution from attributes (e.g., `onerror`).
Install
-
npm install micromark-util-encode -
yarn add micromark-util-encode -
pnpm add micromark-util-encode
Imports
- encode
const { encode } = require('micromark-util-encode')import { encode } from 'micromark-util-encode' - encode (default)
import encode from 'micromark-util-encode'
import { encode } from 'micromark-util-encode' - Types
import type { Value } from 'micromark-util-types'
Quickstart
import { encode } from 'micromark-util-encode';
const unsafeHtml = '<script>alert("XSS")</script> & <img src="x" onerror="alert(\'Error\')">';
const safeHtml = encode(unsafeHtml);
console.log('Original:', unsafeHtml);
console.log('Encoded:', safeHtml);
// Expected output: Original: <script>alert("XSS")</script> & <img src="x" onerror="alert(\'Error\')">
// Expected output: Encoded: <script>alert("XSS")</script> & <img src="x" onerror="alert('Error')">