Skip to content
All posts
8 min read
markdown
html
convert
guide
api

How to Convert Markdown to HTML: 6 Methods Compared (2026)

Convert Markdown to clean HTML for CMS, email, and static sites — browser tools, CLI, JavaScript libraries, static generators, and API pipelines compared with code examples.

"Markdown to HTML" is one of the highest-intent searches in the Markdown ecosystem. Developers need HTML for CMS embeds, email templates, comment systems, and AI output pipelines. Writers need it for WordPress, Substack, and internal wikis.

This guide compares six reliable conversion methods, explains when each wins, and shows copy-paste examples — including how to get sanitized, production-ready HTML without running a headless browser.

TL;DR — pick your method

NeedBest method
One file, right now, no installBrowser converter
React / Next.js appJavaScript library
Docs site from .md filesStatic site generator
CI/CD or backend serviceREST API
Batch CLI on a serverPandoc
Legacy .md + custom macrosBuild script

What "good" HTML output looks like

Before comparing tools, define the bar:

  1. Semantic tags — <h1>–<h6>, <p>, <ul>, <pre><code>, <table>.
  2. GFM support — tables, task lists, strikethrough, autolinks, fenced code with language class.
  3. Sanitization — no <script>, no onclick, no javascript: URLs in untrusted input.
  4. Predictable CSS hooks — classes like language-typescript on code blocks for highlight.js or Prism.
  5. Portable — standalone file or fragment you can drop into any template.

Bad HTML — &lt;div&gt; soup, inline styles on every element, or missing lang on code blocks — breaks downstream styling and accessibility.

Method 1: Browser converter (free)

The fastest path for a single document: paste Markdown, get HTML, copy or download.

How it works

  1. Open the Markdown to HTML converter.
  2. Paste Markdown or drop a .md file.
  3. Copy the HTML output or download a standalone .html file.
  4. Paste into your CMS, email tool, or template.

The editor also exports sanitized HTML with the same renderer used across the site.

Pros

  • Zero install — works in Chrome, Firefox, Safari, Edge.
  • Private — content stays in your browser unless you call an API.
  • Sanitized output — scripts and event handlers stripped.
  • Free — no API key for browser tools.

Cons

  • One document at a time — not for batch builds.
  • No server-side cache — you copy-paste manually.

When to use

README previews, one-off blog migrations, support macros, and "I need HTML in the next 60 seconds."

Method 2: Pandoc (CLI)

Pandoc converts between dozens of formats. For Markdown → HTML:

pandoc README.md -o README.html --standalone

With a table of contents:

pandoc docs.md -o docs.html --standalone --toc --toc-depth=3

Pros

  • Batch-friendly — shell loops over hundreds of files.
  • Template control — custom HTML templates with variables.
  • Format breadth — same tool handles PDF, DOCX, LaTeX.

Cons

  • GFM gaps — task lists and some extensions need gfm input format explicitly:
pandoc input.md -f gfm -t html -o output.html --standalone
  • No built-in sanitization — if input is user-generated, sanitize separately.
  • Install weight — Pandoc + LaTeX is heavy on CI runners.

When to use

Book manuscripts, academic papers, and ops teams already standardized on Pandoc.

Method 3: JavaScript libraries

For apps that render Markdown at runtime or build time in Node/browser.

react-markdown + remark-gfm

import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

export function Post({ source }: { source: string }) {
  return (
    <ReactMarkdown remarkPlugins={[remarkGfm]}>
      {source}
    </ReactMarkdown>
  );
}

marked (minimal)

import { marked } from "marked";

marked.setOptions({ gfm: true });
const html = marked.parse("# Hello\n\n| a | b |\n|---|---|\n| 1 | 2 |");

unified / remark (maximum control)

import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeSanitize from "rehype-sanitize";
import rehypeStringify from "rehype-stringify";

const file = await unified()
  .use(remarkParse)
  .use(remarkGfm)
  .use(remarkRehype)
  .use(rehypeSanitize)
  .use(rehypeStringify)
  .process(markdown);

const html = String(file);

Pros

  • Embedded in your app — no network hop.
  • Plugin ecosystem — math, syntax highlight, custom directives.
  • SSR and CSR — works in Next.js, Remix, Astro.

Cons

  • Bundle size — full parser in client JS adds kilobytes.
  • Version drift — GFM support varies by library version.
  • You own security — must configure sanitization for user content.

When to use

Comment systems, CMS previews, AI chat UIs showing formatted responses.

Method 4: Static site generators

If Markdown files are your site, the SSG converts them at build time.

GeneratorMarkdown stackOutput
HugoGoldmarkHTML pages in public/
Jekyllkramdown / GFM_site/
Astroremarkdist/
DocusaurusMDX + remarkbuild/
Next.jsMDX remoteper-route HTML

Example Hugo page (content/api-quickstart.md):

---
title: "API Quickstart"
date: 2026-06-05
---

# API Quickstart

```bash
curl https://trymarkdownviewer.com/api/v1/health
```

Build:

hugo --minify

Pros

  • SEO-native — full pages with meta, sitemap, RSS.
  • No runtime parse cost — HTML generated once at deploy.
  • Version controlled — docs live next to code.

Cons

  • Build step required — not for dynamic user-generated content.
  • MDX learning curve — components in Markdown add complexity.

When to use

Product documentation, blogs, and docs-as-code workflows.

Method 5: Markdown API (production pipelines)

When Markdown arrives from users, AI models, webhooks, or a CMS API, you need server-side render with consistent output and rate limits.

Render endpoint

curl -X POST https://trymarkdownviewer.com/api/v1/render \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"markdown": "# Hello\n\n| a | b |\n|---|---|\n| 1 | 2 |"}'

Response:

{
  "html": "<h1>Hello</h1>\n<table>...</table>",
  "meta": { "words": 2, "headings": 1 }
}

Why teams choose an API over self-hosting

ConcernSelf-hosted libraryMarkdown Viewer API
SanitizationYou configureDOMPurify by default
GFM parityDepends on versionsMatches browser editor
Ops burdenUpgrade + patch CVEsManaged endpoint
Cost at low volumeFree (your CPU)Free tier 100 req/day

Related endpoints:

Test in the API playground. Full docs: API quickstart.

Pros

  • Same renderer as the browser tools — WYSIWYG across product surface.
  • Scales horizontally — no parser in your app's memory footprint.
  • CI-friendly — GitHub Action can call render on every PR.

Cons

  • Network latency — ~50–200ms per request.
  • Quota limits — plan-based daily limits apply.

When to use

AI apps rendering model output, multi-tenant CMS, email preview services, and mobile apps without a JS runtime.

Method 6: Custom build scripts

Glue method: watch a folder, render each file, write HTML.

import fs from "node:fs";
import path from "node:path";

const API_KEY = process.env.MDV_API_KEY!;
const srcDir = "./content/posts";

for (const file of fs.readdirSync(srcDir)) {
  if (!file.endsWith(".md")) continue;
  const md = fs.readFileSync(path.join(srcDir, file), "utf8");
  const res = await fetch("https://trymarkdownviewer.com/api/v1/render", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ markdown: md }),
  });
  const { html } = await res.json();
  fs.writeFileSync(
    path.join("./public/posts", file.replace(/\.md$/, ".html")),
    wrapLayout(html),
  );
}

Pair with extract frontmatter to split YAML metadata from body before render.

Styling the HTML output

Raw HTML looks unstyled. Three common approaches:

1. Embed in existing CSS framework

<article class="prose prose-slate dark:prose-invert">
  <!-- rendered HTML -->
</article>

Tailwind Typography (@tailwindcss/typography) styles semantic HTML with one class.

2. Inline critical CSS

The Markdown to HTML tool can download a standalone .html with embedded styles — useful for email snapshots and offline sharing.

3. Syntax highlighting pass

Add highlight.js after render:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>

The API returns class="language-ts" on fenced blocks — highlight.js picks it up automatically.

Security: never skip sanitization on user input

Markdown can embed HTML. Attackers inject:

[click me](javascript:alert(1))

<img src=x onerror=alert(1)>

Rules:

  • Your own docs — lower risk; still sanitize if collaborators use PRs.
  • User comments, AI output, form fields — always sanitize.
  • API render endpoint — DOMPurify strips scripts and dangerous URLs by default.

For defense in depth, run validate before render in untrusted pipelines.

Markdown → HTML for specific platforms

DestinationGotchaFix
WordPressBlocks expect HTML or shortcodesPaste HTML block; strip <html> wrapper
SubstackLimited tagsSimplify to <p>, <h2>, <a>, <img>
Email (Mailchimp)Inline CSS requiredUse a post-processor like Premailer
React dangerouslySetInnerHTMLXSS riskSanitize + CSP headers
Shopify product descStrips <script>Already safe; avoid custom JS

Convert platform-specific HTML back to Markdown with HTML to Markdown when migrating between systems.

Comparison table

MethodSpeedGFMSanitizedBatchCost
Browser tool⚡⚡⚡✅✅❌Free
Pandoc⚡⚡⚠️❌✅Free
JS library⚡⚡✅⚠️✅Free
SSG⚡ (build)✅N/A✅Free
REST API⚡⚡✅✅✅Free tier
Custom script⚡⚡✅✅✅API usage

Common mistakes

1. Rendering unsanitized user Markdown. The #1 XSS vector in comment systems.

2. Expecting CSS from the converter. HTML is structure; you bring styles.

3. Losing code language classes. Fenced blocks need language-* for highlighting — verify your pipeline preserves them.

4. Wrapping fragments in full <html> documents twice. CMS fields want fragments, not documents.

5. Using innerHTML without a content policy. Pair sanitization with CSP script-src 'self'.

6. Pandoc without -f gfm. Tables silently break.

Try it now

Markdown to HTML is a solved problem — the only question is whether you need a browser click, a build step, or an API call. Pick the row in the comparison table that matches your constraint and ship.

Written by Markdown Viewer Team. Found this useful? Try the editor →

Keep reading

Hand-picked articles related to this one.