commonmark vs markdown-it vs remark vs showdown
Parsing and Rendering Markdown in JavaScript Applications
commonmarkmarkdown-itremarkshowdownSimilar Packages:

Parsing and Rendering Markdown in JavaScript Applications

commonmark, markdown-it, remark, and showdown are JavaScript libraries used to parse Markdown text and convert it into other formats, primarily HTML. showdown is one of the oldest, focusing on ease of use with a regex-based parser. commonmark is the strict reference implementation of the CommonMark spec, prioritizing spec compliance over extensibility. markdown-it is a high-performance parser that uses a token-based approach, offering a rich plugin ecosystem for rendering HTML. remark is part of the unified ecosystem, using an Abstract Syntax Tree (AST) to transform Markdown, making it ideal for complex transformations beyond simple HTML rendering.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
commonmark01,557673 kB522 years agoBSD-2-Clause
markdown-it021,507777 kB209 days agoMIT
remark08,89615.7 kB83 years agoMIT
showdown014,863801 kB235-MIT

Parsing and Rendering Markdown: commonmark vs markdown-it vs remark vs showdown

When building applications that handle user-generated content, documentation, or static sites, choosing the right Markdown parser is critical. commonmark, markdown-it, remark, and showdown all solve the same core problem but take vastly different architectural approaches. Let's compare how they handle parsing, extensibility, and output generation.

🧠 Core Architecture: Regex vs Tokens vs AST

The fundamental difference lies in how these libraries process text.

showdown uses a regex-based approach.

  • It applies a series of regular expressions to transform Markdown into HTML.
  • Fast to set up but can struggle with complex nested structures.
// showdown: Regex-based conversion
import showdown from 'showdown';

const converter = new showdown.Converter();
const html = converter.makeHtml('# Hello World');
// Output: <h1>Hello World</h1>

commonmark is a strict reference implementation.

  • It follows the CommonMark spec exactly, ensuring consistent output.
  • Less flexible for custom extensions but highly predictable.
// commonmark: Spec-compliant parsing
import commonmark from 'commonmark';

const reader = new commonmark.Parser();
const writer = new commonmark.HtmlRenderer();
const parsed = reader.parse('# Hello World');
const html = writer.render(parsed);
// Output: <h1>Hello World</h1>

markdown-it uses a token-based streaming parser.

  • It breaks input into tokens, which are then rendered to HTML.
  • Offers a balance of speed and extensibility via plugins.
// markdown-it: Token-based parsing
import markdownit from 'markdown-it';

const md = markdownit();
const html = md.render('# Hello World');
// Output: <h1>Hello World</h1>

remark uses an Abstract Syntax Tree (AST).

  • It parses Markdown into a tree structure (mdast) that can be manipulated.
  • Best for complex transformations beyond simple HTML rendering.
// remark: AST-based processing
import { remark } from 'remark';
import remarkHtml from 'remark-html';

const file = await remark()
  .use(remarkHtml)
  .process('# Hello World');

const html = String(file);
// Output: <h1>Hello World</h1>

🔌 Extensibility: Plugins and Custom Syntax

Real-world apps often need custom syntax (e.g., alerts, emojis, or video embeds).

showdown supports extensions via a callback system.

  • You define regex patterns to replace or modify content.
  • Simple but can become messy with complex logic.
// showdown: Custom extension
showdown.extension('headerId', function () {
  return [{
    type: 'output',
    regex: /<h(\d)>(.*?)<\/h\1>/g,
    replace: (match, level, content) => `<h${level} id="${content}">${content}</h${level}>`
  }];
});

commonmark does not support plugins natively.

  • To add features, you must fork the parser or wrap it.
  • Best for projects that want zero deviation from the spec.
// commonmark: No native plugin support
// Custom logic requires manual AST traversal after parsing
const reader = new commonmark.Parser();
const parsed = reader.parse('# Hello');
// Manually walk 'parsed' tree to modify nodes before rendering

markdown-it has a rich plugin ecosystem.

  • Plugins can add new tokens or modify existing ones.
  • Easy to enable features like tables, footnotes, or emojis.
// markdown-it: Plugin usage
import markdownit from 'markdown-it';
import emoji from 'markdown-it-emoji';

const md = markdownit().use(emoji);
const html = md.render(':smile:');
// Output: <p>😄</p>

remark relies on the unified plugin ecosystem.

  • Plugins transform the AST, allowing deep customization.
  • You can lint, format, or convert to any format (HTML, PDF, etc.).
// remark: Plugin usage
import { remark } from 'remark';
import remarkGfm from 'remark-gfm';

const file = await remark()
  .use(remarkGfm) // Enables tables, strikethrough, etc.
  .process('# Hello~world~');

console.log(String(file));

🌳 AST Manipulation: Inspecting and Modifying Content

If you need to analyze or modify the document structure (e.g., extracting headings, checking links), the AST approach shines.

showdown does not expose an AST.

  • You get HTML string output directly.
  • Modifying structure requires parsing the HTML again (e.g., with DOMParser).
// showdown: No AST access
const html = converter.makeHtml('# Title');
// To modify, you must parse 'html' string with DOM tools

commonmark exposes a node tree but it is less flexible.

  • You can walk the tree, but tooling is minimal compared to unified.
// commonmark: Basic tree walking
const walker = parsed.walker();
let event;
while ((event = walker.next())) {
  const node = event.node;
  if (node.type === 'heading') { /* ... */ }
}

markdown-it exposes tokens, not a full AST.

  • Tokens are linear and easier to render but harder to transform structurally.
// markdown-it: Token inspection
const tokens = md.parse('# Title');
tokens.forEach(token => {
  if (token.type === 'heading_open') { /* ... */ }
});

remark is built for AST manipulation.

  • You can write plugins to visit, add, or remove nodes easily.
  • Ideal for linting or generating tables of contents.
// remark: AST transformation plugin
import { visit } from 'unist-util-visit';

const extractHeadings = () => (tree) => {
  const headings = [];
  visit(tree, 'heading', (node) => headings.push(node));
  console.log(headings);
};

await remark().use(extractHeadings).process('# Title');

⚡ Performance and Bundle Considerations

Performance varies based on input size and feature set.

showdown is lightweight but can slow down on large documents.

  • Regex operations scale poorly with complex nesting.
  • Good for small inputs or client-side rendering.
// showdown: Simple setup, potential perf cost on large text
const converter = new showdown.Converter();
const html = converter.makeHtml(largeMarkdownString);

commonmark is optimized for spec compliance, not speed.

  • Consistent performance but lacks optimizations for web-specific use cases.
// commonmark: Stable performance
const parsed = reader.parse(largeMarkdownString);
const html = writer.render(parsed);

markdown-it is highly optimized for speed.

  • Designed for high-throughput environments like forums or CMSs.
  • Often faster than showdown for typical web content.
// markdown-it: High performance rendering
const html = md.render(largeMarkdownString);

remark has higher overhead due to AST construction.

  • Best suited for build-time processing rather than real-time client rendering.
  • The trade-off is flexibility and transform power.
// remark: Build-time processing
const file = await remark().use(remarkHtml).process(largeMarkdownString);

🛡️ Security: Sanitization and XSS

Markdown parsers can introduce XSS vulnerabilities if they allow raw HTML.

showdown allows raw HTML by default.

  • You must enable sanitize: true to prevent script injection.
  • Easy to miss, leading to potential security risks.
// showdown: Security config
const converter = new showdown.Converter({ sanitize: true });

commonmark blocks raw HTML by default.

  • Safer out of the box but requires configuration to allow safe tags.
  • Reduces risk of accidental XSS.
// commonmark: Safe by default
// Raw HTML tags in input are escaped automatically

markdown-it allows raw HTML by default.

  • You need to use a plugin like markdown-it-sanitizer or external tools.
  • Flexible but requires manual security setup.
// markdown-it: Manual sanitization
import sanitize from 'markdown-it-sanitizer';
const md = markdownit().use(sanitize);

remark does not sanitize by default.

  • You must add rehype-sanitize in the pipeline for safety.
  • Gives full control but puts responsibility on the developer.
// remark: Sanitization plugin
import rehypeSanitize from 'rehype-sanitize';
import remarkRehype from 'remark-rehype';

await remark()
  .use(remarkRehype)
  .use(rehypeSanitize)
  .process(markdownContent);

📊 Summary: Key Differences

Featureshowdowncommonmarkmarkdown-itremark
ArchitectureRegexSpec ReferenceToken-basedAST (unified)
ExtensibilityExtensions (Regex)Low (Manual)High (Plugins)Very High (Plugins)
OutputHTML StringHTML StringHTML StringAny (via plugins)
SecurityConfigurableSafe DefaultConfigurableManual (via plugins)
Best Use CaseSimple AppsSpec ComplianceContent SitesBuild Tools / Transforms

💡 The Big Picture

showdown is the old reliable 🛠️—easy to drop in for simple HTML conversion, but be careful with security settings. Great for legacy apps or quick prototypes.

commonmark is the strict librarian 📚—ensures everyone sees the exact same output according to the spec. Use when consistency across different systems is non-negotiable.

markdown-it is the speedster 🏎️—perfect for rendering content to HTML quickly with plenty of plugin options. Ideal for blogs, documentation, and forums.

remark is the transformer 🤖—best for build pipelines where you need to analyze, modify, or convert Markdown into various formats. Essential for static site generators and complex tooling.

Final Thought: If you just need HTML, markdown-it is usually the sweet spot. If you are building a tool that processes Markdown files (like a linter or generator), remark is the industry standard. Avoid showdown for new security-sensitive projects unless you strictly configure sanitization.

How to Choose: commonmark vs markdown-it vs remark vs showdown

  • commonmark:

    Choose commonmark if strict adherence to the CommonMark specification is your top priority and you need a predictable, stable parser without extra features. It is best suited for scenarios where spec compliance matters more than custom extensions or performance tweaks, such as documentation systems that must render identically across platforms.

  • markdown-it:

    Choose markdown-it if you need a fast, flexible parser for rendering Markdown to HTML with a wide range of plugins. It is ideal for content management systems, blogs, or forums where you need to support custom syntax (like emojis or containers) without sacrificing speed or stability.

  • remark:

    Choose remark if you need to transform Markdown into other formats (like HTML, PDF, or even other Markdown variants) using a robust plugin ecosystem based on an Abstract Syntax Tree. It is the best choice for build tools, static site generators, or complex document processing pipelines where you need to inspect or modify the document structure.

  • showdown:

    Choose showdown if you need a simple, battle-tested library for basic Markdown-to-HTML conversion with minimal setup. It is suitable for legacy projects or simple applications where advanced AST manipulation or strict spec compliance is not required, and you prefer a straightforward API.

README for commonmark

commonmark.js

Build Status NPM version

CommonMark is a rationalized version of Markdown syntax, with a spec and BSD-licensed reference implementations in C and JavaScript.

For more information, see http://commonmark.org.

This repository contains the JavaScript reference implementation. It provides a library with functions for parsing CommonMark documents to an abstract syntax tree (AST), manipulating the AST, and rendering the document to HTML or to an XML representation of the AST.

To play with this library without installing it, see the live dingus at http://try.commonmark.org/.

Installing

You can install the library using npm:

npm install commonmark

This package includes the commonmark library and a command-line executable, commonmark.

For client-side use, you can use one of the single-file distributions provided in the dist/ subdirectory of the node installation (node_modules/commonmark/dist/). Use either commonmark.js (readable source) or commonmark.min.js (minimized source).

Alternatively, bower install commonmark will install the needed distribution files in bower_components/commonmark/dist.

You can also use the version hosted by unpkg: for example, https://unpkg.com/commonmark@0.29.3/dist/commonmark.js for the unminimized version 0.29.3.

Building

Make sure to fetch dependencies with:

npm install

To run tests for the JavaScript library:

npm test

(Running the tests will also rebuild distribution files in dist/.)

To run benchmarks against some other JavaScript converters:

make bench

To start an interactive dingus that you can use to try out the library:

make dingus

Usage

Instead of converting Markdown directly to HTML, as most converters do, commonmark.js parses Markdown to an AST (abstract syntax tree), and then renders this AST as HTML. This opens up the possibility of manipulating the AST between parsing and rendering. For example, one could transform emphasis into ALL CAPS.

Here's a basic usage example:

var reader = new commonmark.Parser();
var writer = new commonmark.HtmlRenderer();
var parsed = reader.parse("Hello *world*"); // parsed is a 'Node' tree
// transform parsed if you like...
var result = writer.render(parsed); // result is a String

The constructors for Parser and HtmlRenderer take an optional options parameter:

var reader = new commonmark.Parser({smart: true});
var writer = new commonmark.HtmlRenderer({sourcepos: true});

Parser currently supports the following:

  • smart: if true, straight quotes will be made curly, -- will be changed to an en dash, --- will be changed to an em dash, and ... will be changed to ellipses.

Both HtmlRenderer and XmlRenderer (see below) support these options:

  • sourcepos: if true, source position information for block-level elements will be rendered in the data-sourcepos attribute (for HTML) or the sourcepos attribute (for XML).
  • safe: if true, raw HTML will not be passed through to HTML output (it will be replaced by comments), and potentially unsafe URLs in links and images (those beginning with javascript:, vbscript:, file:, and with a few exceptions data:) will be replaced with empty strings.
  • softbreak: specify raw string to be used for a softbreak.
  • esc: specify a function to be used to escape strings. Its argument is the string.

For example, to make soft breaks render as hard breaks in HTML:

var writer = new commonmark.HtmlRenderer({softbreak: "<br />"});

To make them render as spaces:

var writer = new commonmark.HtmlRenderer({softbreak: " "});

XmlRenderer serves as an alternative to HtmlRenderer and will produce an XML representation of the AST:

var writer = new commonmark.XmlRenderer({sourcepos: true});

The parser returns a Node. The following public properties are defined (those marked "read-only" have only a getter, not a setter):

  • type (read-only): a String, one of text, softbreak, linebreak, emph, strong, html_inline, link, image, code, document, paragraph, block_quote, item, list, heading, code_block, html_block, thematic_break.
  • firstChild (read-only): a Node or null.
  • lastChild (read-only): a Node or null.
  • next (read-only): a Node or null.
  • prev (read-only): a Node or null.
  • parent (read-only): a Node or null.
  • sourcepos (read-only): an Array with the following form: [[startline, startcolumn], [endline, endcolumn]].
  • isContainer (read-only): true if the Node can contain other Nodes as children.
  • literal: the literal String content of the node or null.
  • destination: link or image destination (String) or null.
  • title: link or image title (String) or null.
  • info: fenced code block info string (String) or null.
  • level: heading level (Number).
  • listType: a String, either bullet or ordered.
  • listTight: true if list is tight.
  • listStart: a Number, the starting number of an ordered list.
  • listDelimiter: a String, either ) or . for an ordered list.
  • onEnter, onExit: Strings, used only for custom_block or custom_inline.

Nodes have the following public methods:

  • appendChild(child): Append a Node child to the end of the Node's children.
  • prependChild(child): Prepend a Node child to the beginning of the Node's children.
  • unlink(): Remove the Node from the tree, severing its links with siblings and parents, and closing up gaps as needed.
  • insertAfter(sibling): Insert a Node sibling after the Node.
  • insertBefore(sibling): Insert a Node sibling before the Node.
  • walker(): Returns a NodeWalker that can be used to iterate through the Node tree rooted in the Node.

The NodeWalker returned by walker() has two methods:

  • next(): Returns an object with properties entering (a boolean, which is true when we enter a Node from a parent or sibling, and false when we reenter it from a child). Returns null when we have finished walking the tree.
  • resumeAt(node, entering): Resets the iterator to resume at the specified node and setting for entering. (Normally this isn't needed unless you do destructive updates to the Node tree.)

Here is an example of the use of a NodeWalker to iterate through the tree, making transformations. This simple example converts the contents of all text nodes to ALL CAPS:

var walker = parsed.walker();
var event, node;

while ((event = walker.next())) {
  node = event.node;
  if (event.entering && node.type === 'text') {
    node.literal = node.literal.toUpperCase();
  }
}

This more complex example converts emphasis to ALL CAPS:

var walker = parsed.walker();
var event, node;
var inEmph = false;

while ((event = walker.next())) {
  node = event.node;
  if (node.type === 'emph') {
    if (event.entering) {
      inEmph = true;
    } else {
      inEmph = false;
      // add Emph node's children as siblings
      while (node.firstChild) {
        node.insertBefore(node.firstChild);
      }
      // remove the empty Emph node
      node.unlink()
    }
  } else if (inEmph && node.type === 'text') {
      node.literal = node.literal.toUpperCase();
  }
}

Exercises for the reader: write a transform to

  1. De-linkify a document, transforming links to regular text.
  2. Remove all raw HTML (html_inline and html_block nodes).
  3. Run fenced code blocks marked with a language name through a syntax highlighting library, replacing them with an HtmlBlock containing the highlighted code.
  4. Print warnings to the console for images without image descriptions or titles.

Command line

The command line executable parses CommonMark input from the specified files, or from stdin if no files are specified, and renders the result to stdout as HTML. If multiple input files are specified, their contents are concatenated before parsing, with newlines between them.

commonmark inputfile.md > outputfile.html
commonmark intro.md chapter1.md chapter2.md > book.html

Use commonmark --help to get a summary of options.

A note on security

The library does not attempt to sanitize link attributes or raw HTML. If you use this library in applications that accept untrusted user input, you should either enable the safe option (see above) or run the output through an HTML sanitizer to protect against XSS attacks.

Performance

Performance is excellent, roughly on par with marked. On a benchmark converting an 11 MB Markdown file built by concatenating the Markdown sources of all localizations of the first edition of Pro Git by Scott Chacon, the command-line tool, commonmark is just a bit slower than the C program discount, roughly ten times faster than PHP Markdown, a hundred times faster than Python Markdown, and more than a thousand times faster than Markdown.pl.

Here are some focused benchmarks of four JavaScript libraries (using versions available on 24 Jan 2015). They test performance on different kinds of Markdown texts. (Most of these samples are taken from the markdown-it repository.) Results show a ratio of ops/second (higher is better) against showdown (which is usually the slowest implementation). Versions: showdown 1.3.0, marked 0.3.5, commonmark.js 0.22.1, markdown-it 5.0.2, node 5.3.0. Hardware: 1.6GHz Intel Core i5, Mac OSX.

Sampleshowdowncommonmarkmarkedmarkdown-it
README.md13.63.13.9
block-bq-flat.md14.84.94.9
block-bq-nested.md111.96.810.7
block-code.md14.712.123.0
block-fences.md16.221.219.1
block-heading.md15.04.86.5
block-hr.md13.53.33.5
block-html.md12.10.93.8
block-lheading.md15.14.93.9
block-list-flat.md14.74.47.4
block-list-nested.md19.57.817.6
block-ref-flat.md10.80.50.6
block-ref-nested.md10.70.60.9
inline-autolink.md12.33.42.5
inline-backticks.md17.65.38.2
inline-em-flat.md11.51.11.6
inline-em-nested.md11.81.31.7
inline-em-worst.md12.41.52.5
inline-entity.md12.03.82.7
inline-escape.md12.21.45.0
inline-html.md12.93.73.3
inline-links-flat.md12.72.72.2
inline-links-nested.md11.40.50.5
inline-newlines.md12.32.03.5
lorem1.md16.02.93.3
rawtabs.md14.63.96.7

To generate this table:

make bench-detailed

Authors

John MacFarlane wrote the first version of the JavaScript implementation. The block parsing algorithm was worked out together with David Greenspan. Kārlis Gaņģis helped work out a better parsing algorithm for links and emphasis, eliminating several worst-case performance issues. Vitaly Puzrin has offered much good advice about optimization and other issues.